I am trying to test different endpoints with a express server.
here is my app.js
const express = require('express');
const app = express();
const cors = require('cors');
const port = 5000;
const dogFunctions = require('./Models/Dog')
const { Pool, Client } = require('pg')
app.use(cors());
app.use(express.json());
const dogRoutes = require('./routes/dogs');
app.use('/dogs', dogRoutes);
app.get('/', (req, res) => res.send('Hello, world!'))
module.exports = app;
this is my config file for testing
const { Pool } = require('pg');
const fs = require('fs');
const request = require('supertest');
const apiServer = require('../../app');
const reset = fs.readFileSync(__dirname + '/reset.sql').toString();
// enable resetting of db between tests
const resetTestDB = () => {
return new Promise (async (res, rej) => {
try {
const db = new Pool();
await db.query(reset)
res('Test DB reset')
} catch (err) {
rej('Could not reset TestDB')
}
})
}
// make these things available to test suites
global.request = request
global.app = apiServer
global.resetTestDB = resetTestDB
here is one of the test files of mine:
describe('dogs endpoints', () => {
let api;
beforeEach(async () => {
await resetTestDB()
})
beforeAll(async () => {
api = app.listen(5000, () => console.log('Test server running on port 5000'))
});
})
here is what my package.json looks like
"scripts": {
"test": "jest --watchAll",
},
"jest": {
"testEnvironment": "node",
"coveragePathIgnorePatterns": [
"/node_modules/"
]
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"pg": "^8.8.0"
},
"devDependencies": {
"jest": "^29.3.0",
"supertest": "^6.3.1"
}
}
What have i done wrong here?
I think its something simple.. but cant figure it out.
I am using global of jest to attach my express to be able available as app in my test files as a global variable.
I have also set my test env to be node to be able to test for node applications.
Is there anything i missed?
I have an express server, which works locally, but when I deploy it to App Engine and send a request I get the response that it has been blocked by CORS policy. If I remove the section where I call exec (and move send response) there is no error.
Why could this be happening?
My code:
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { exec } = require('child_process');
const app = express();
app.use(bodyParser.json());
app.use(cors());
module.exports = app
app.post("/", (req,res) =>{
console.log("Get from /");
console.log(req.body.data)
//IF I COMMENT EXEC OUT IT WORKS
exec('npx hardhat run scripts/deploy.js --network goerli',
(error, stdout, stderr) => {
if (error !== null) {
console.log(`exec error: ${error}`);
}
else{
res.send("response");
}
})
});
app.listen(8080, () => {
console.log('listening on port 8080');
});
This is my package.json:
{
"name": "hardhat-project",
"devDependencies": {
"#nomiclabs/hardhat-ethers": "^2.0.6",
"ethers": "^5.6.9",
"hardhat": "^2.9.9"
},
"version": "1.0.0",
"description": "smart contract",
"main": "hardhat.config.js",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.1",
"firebase-admin": "^11.0.0"
},
"scripts": {
"start": "node src/index.js",
"test": "mocha"
},
"author": "",
"license": "ISC"
}
A screenshot of the error:
Been trying to deploy my create-react app (MERN stack) app to Heroku and having problems getting anything React related to display in Heroku. On my local computer it works perfectly fine. In Heroku however when I hit any route it just displays the json that I am serving from my back-end. The json has all my database information in it which tells me that my back-end and my MongoDB are hooked up and working correctly. However, no React components are being displayed. I have tried adding a static.json file, tinkered with heroku-postbuild scripts, and tinkered with different code in the server.js file that serves the static index.html file from other posts but with no success. Any help in getting my front-end to display in Heroku would be much much appreciated!
Link to my code in Github
github
Folder Structure
Client package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"proxy": "https://youth-sports.herokuapp.com",
"homepage": "https://youth-sports.herokuapp.com",
"dependencies": {
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^11.2.7",
"#testing-library/user-event": "^12.8.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^5.3.0",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"node-sass": "^6.0.1"
}
}
Root/Server-side package.json
{
"name": "youth-sports",
"version": "1.0.0",
"description": "",
"main": "sever.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"dev": "nodemon server.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client"
},
"author": "Shaun Valentine",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^6.0.12"
}
}
server.js file
require('dotenv').config();
const Players = require('./Model/playersModel.js'); //!Importing players model into backend for now to serve front-end React
const express = require('express');
const app = express();
const path = require('path');
const PORT = process.env.PORT || 5000;
const mongoose = require('mongoose');
const MONGODB_URI = process.env.MONGODB_URI;
const db = mongoose.connection;
mongoose.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
db.on('open', () => {
console.log('Mongo is Connected');
});
//? MIDDLEWARE
app.use(express.json());
if (process.env.NODE_ENV !== 'development') {
app.use(express.static('public'));
// app.use('/static', express.static(path.join(__dirname, 'build')));
}
// app.use(express.json());
// if (process.env.NODE_ENV === 'production') {
// // app.use(express.static('public'));
// app.use(express.static(path.join(__dirname, 'build')));
// }
const cors = require('cors');
app.use(cors());
app.use(express.urlencoded({ extended: true })); // Middleware - so we can use req.body otherwise Express can't read what's in the body of our POST request. This Middleware parses data from forms in the x-www-form-urlencoded format
app.use(express.json()); // Middleware - for parsing data coming in the body of the POST request as json format
//? GET REQUEST - INDEX ROUTE - SHOW ALL PLAYERS UPON HITTING THIS ROUTE
app.get('/players', async (req, res) => {
try {
const roster = await Players.find({});
res.json(roster);
} catch (error) {
res.status(400).json(error);
}
});
//? GET REQUEST - SHOW PAGE (INDIVIDUAL PLAYER)
app.get('/players/:id', async (req, res) => {
try {
const playerProfile = await Players.findById(req.params.id);
res.status(200).json(playerProfile);
console.log(playerProfile);
} catch (error) {
res.status(400).send(error);
}
});
//? POST REQUEST - CREATE ROUTE - POST NEW PLAYER DATA TO MONGODB FROM NEW PLAYER FORM ON NewPlayer.js file
app.post('/players', async (req, res) => {
try {
console.log(req.body);
await Players.create(req.body);
res.redirect('/players');
} catch (error) {
console.log(error);
}
});
app.get('/teams', async (req, res) => {
try {
await res.json({ message: 'Hello from server!!!' });
} catch (error) {
console.log(error);
}
});
app.get('*', (req, res) => {
res.sendFile(
path.resolve(path.join(__dirname, 'client', 'public', 'index.html'))
);
// res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
// res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(PORT, () => {
console.log(`Listening on PORT ${PORT} yo`);
});
App.js file (client file)
import './Sass/App.scss';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; //! MUST IMPORT BrowserRouter (changing name to just Router is optional) and Route and Switch
import NewPlayer from './Components/NewPlayer.js';
import Rosters from './Views/Rosters.js';
import PlayerProfile from './Views/PlayerProfile.js';
import Home from './Views/Home.js';
import './Sass/App.scss';
function App() {
return (
<div className="App">
<Router>
<Switch>
<Route exact path="/players">
<Rosters />
</Route>
<Route exact path="/players/new">
<NewPlayer />
</Route>
<Route exact path="/players/:id">
<PlayerProfile />
</Route>
<Route exact path="/">
<Home />
</Route>
</Switch>
</Router>
</div>
);
}
export default App;
static.json
{
"root": "build/",
"clean_urls": false,
"routes": {
"/**": "index.html"
}
}
Make the following updates.
We have to serve the static files of the build folder of the react-app to the server.
Root/Server-side package.json
{
"name": "youth-sports",
"version": "1.0.0",
"description": "",
"main": "sever.js",
"scripts": {
"start": "node server.js",
"heroku-postbuild": "npm run client-install && npm run client-build",
"client-install": "cd client && npm install",
"client-build": "cd client && npm run build"
},
"author": "Shaun Valentine",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^6.0.12"
}
}
server.js file
require('dotenv').config();
const Players = require('./Model/playersModel.js'); //!Importing players model into backend for now to serve front-end React
const express = require('express');
const app = express();
const path = require('path');
const PORT = process.env.PORT || 5000;
const mongoose = require('mongoose');
const MONGODB_URI = process.env.MONGODB_URI;
const db = mongoose.connection;
mongoose.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
db.on('open', () => {
console.log('Mongo is Connected');
});
//? MIDDLEWARE
app.use(express.json());
if (process.env.NODE_ENV !== 'development') {
app.use(express.static('public'));
// app.use('/static', express.static(path.join(__dirname, 'build')));
}
const cors = require('cors');
app.use(cors());
app.use(express.urlencoded({ extended: true })); // Middleware - so we can use req.body otherwise Express can't read what's in the body of our POST request. This Middleware parses data from forms in the x-www-form-urlencoded format
app.use(express.json()); // Middleware - for parsing data coming in the body of the POST request as json format
//? GET REQUEST - INDEX ROUTE - SHOW ALL PLAYERS UPON HITTING THIS ROUTE
app.get('/players', async (req, res) => {
try {
const roster = await Players.find({});
res.json(roster);
} catch (error) {
res.status(400).json(error);
}
});
//? GET REQUEST - SHOW PAGE (INDIVIDUAL PLAYER)
app.get('/players/:id', async (req, res) => {
try {
const playerProfile = await Players.findById(req.params.id);
res.status(200).json(playerProfile);
console.log(playerProfile);
} catch (error) {
res.status(400).send(error);
}
});
//? POST REQUEST - CREATE ROUTE - POST NEW PLAYER DATA TO MONGODB FROM NEW PLAYER FORM ON NewPlayer.js file
app.post('/players', async (req, res) => {
try {
console.log(req.body);
await Players.create(req.body);
res.redirect('/players');
} catch (error) {
console.log(error);
}
});
app.get('/teams', async (req, res) => {
try {
await res.json({ message: 'Hello from server!!!' });
} catch (error) {
console.log(error);
}
});
app.listen(PORT, () => {
console.log(`Listening on PORT ${PORT} yo`);
});
According to online tutorials i ran npm run build in the react app and then pasted the build folder in the server directory but i think it is just serving the server side, i am unable to figure out the problem , please help me what is the error in its deployment
My index.js
const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const path = require("path")
const { MONGODB } = require("./config");
const model = require("./models/user");
const router = require("./Routes/auth");
const PORT = process.env.PORT || 8000;
/***********************************config ************************* */
mongoose.connect(MONGODB, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on("connected", () => {
console.log("connected to mongoDb");
});
/********************model imports ***************************/
const User = require("./models/user");
const Post = require("./models/post");
/********************************middlewares**************************** */
app.use(express.json());
app.use(cors());
app.use(router);
app.use(require("./Routes/posts"));
app.use(require("./Routes/user"));
/****code related to production of app***** */
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
/**********************listening on server *********************** */
app.listen(PORT, (err) => {
if (err) {
return console.log(`Error: ${err}`);
}
console.log(`server running on port: ${PORT}`);
});
my package.json - server
{
"name": "instagram-clone",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.12.4",
"nodemon": "^2.0.7",
"path": "^0.12.7"
}
}
Github link: https://github.com/dhruv354/insta-app.git
so, it just says 'cannot GET /' everytime i try to view my app
here is the code
server.js
//Import requiered packages
const express = require('express');
const {Client} = require('pg');
//Create the conection to the postgres server
const client = new Client({
connectionString: process.env.DATABASE_URL
});
client.connect();
//Create the express app
const bodyParser = require('body-parser');
const app = express();
// parse application/json
app.use(bodyParser.json());
//Handle a post request at /query
app.post('/query', (req, res) => {
res.setHeader('Content-Type', 'application/json');
console.log("Receiving request");
if(req.body.query) {
console.log(req.body.query);
client.query(req.body.query, (err, r) => {
if (err) throw err;
rows = [];
for(let row of r.rows){
rows.push(row);
}
response = JSON.stringify(rows);
console.log(response);
res.end(response);
});
}
});
const port = process.env.PORT || 8080
//Start listening
const server = app.listen(port, function () {
console.log("App listening at ${host}")
});
package.json
{
"name": "haha",
"description": "joseph = obesity > lawa",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "4.x.x",
"pg": "7.x.x",
"body-parser": "1.18.x"
}
}
I literally have no clue what's wrong and theres almost no erroirs in the CLI.
The errors in the CLI are basically irrelevant to this, as even if tehre are no errors im still presented with the 'cannot GET /' message
please help me :(