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:
Related
I'm trying to figure out a last assignment for my boot camp and am close to running out of time.
Heroku has an application error and I can't figure out how to fix it. I've tried deleting and reinstalling node modules, adding node and npm versions in my package.json, npm update, heroku restart, changing my PORT and have rewritten my connection and server files several times. I'm losing track of what I've tried. I think I might be missing something when it comes to MongoDB or Apollo, both of which I'm required to use, but I don't know what. I added keys to my .env and I don't know if I've done it wrong or something but it just won't work on Heroku. It works locally.
Here is my package.json currently.
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"watch": "nodemon server.js"
},
"keywords": [],
"author": "Wren Sanchez",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.0",
"express": "^4.17.1",
"dotenv": "^16.0.1",
"graphql": "^15.5.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.9.10",
"apollo-server-express": "^3.6.1",
"nodemon": "^2.0.3"
},
"devDependencies": {
"nodemon": "^2.0.3"
}
}
My server.js
const { ApolloServer } = require("apollo-server-express");
const express = require('express');
const path = require('path');
const db = require('./config/connection');
const { typeDefs, resolvers } = require("./schemas");
const { authMiddleware } = require('./utils/auth');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3001;
const server = new ApolloServer({
typeDefs,
resolvers,
context: authMiddleware,
cache: "bounded",
});
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '../client/build')));
}
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../client/build/index.html'));
});
const startApolloServer = async (typeDefs, resolvers) => {
await server.start();
server.applyMiddleware({ app });
db.once("open", () => {
app.listen(PORT, () => {
console.log(`API server running on port ${PORT}!`);
console.log(
`Use GraphQL at http://localhost:${PORT}${server.graphqlPath}`
);
});
});
startApolloServer(typeDefs, resolvers);
}
My connection.js
const mongoose = require('mongoose');
require('dotenv').config({ path: '../.env' });
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/googlebooks', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
module.exports = mongoose.connection;
And if useful, my repository: https://github.com/wrenvana/Book-Search-Engine
Any help is appreciated, we have been learning React and MERN at the very end and I've been having a hard time with it.
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
I have created a react app using create-react-app and an express server using express-generator. My react app is running on http://localhost:3000 and my express server is running on http://localhost:8080. In my component I am making a POST fetch request to my express server, which is successfully running my express router code, returning a 200 response status code. However, the client console logs the following error and does not receive the response:
Proxy error: Could not proxy request /components/findAlbumArt from localhost:3000 to http://localhost:8080.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).
In the browser under the network tab I can see that the findAlbumArt request now has the status (canceled).
My react code:
import React, { Component } from "react";
class Search extends Component {
constructor(props) {
super(props);
this.state = { value: "" };
}
handleChange = (event) => {
this.setState({ value: event.target.value });
};
handleSubmit = async (event) => {
let response = await fetch("/components/findAlbumArt", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
value: this.state.value,
}),
});
response = await response.json();
this.props.setAlbumArt(response.albumArtUrl);
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Find an album that you love:{" "}
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
</label>{" "}
<input type="submit" value="Submit" />
</form>
);
}
}
export default Search;
My express code:
const express = require("express");
const cache = require("../bin/cache/cache");
const axios = require("axios");
const router = express.Router();
router.post("/findAlbumArt", async (req, res, next) => {
res
.status(200)
.json({
albumArtUrl:
"https://i.scdn.co/image/ab67616d0000b2739feadc48ab0661e9b3a9170b",
});
// I commented out my other code to simply test returning a success response
});
module.exports = router;
Other relevant files:
app.js
const express = require("express");
const path = require("path");
const createError = require("http-errors");
const logger = require("morgan");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
let app = express();
const indexRouter = require("./routes/index");
const componentsRouter = require("./routes/components");
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use("/components", componentsRouter);
app.use("/", indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
module.exports = app;
express package.json
{
"name": "onboarding",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "nodemon ./bin/www",
"start": "node ./bin/www"
},
"dependencies": {
"async-redis": "^1.1.7",
"axios": "^0.19.2",
"body-parser": "^1.19.0",
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"morgan": "~1.9.1",
"pug": "2.0.0-beta11"
}
}
client package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:8080",
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Any help would be greatly appreciated. Thank you!
Solved the problem myself actually. I was missing event.preventDefault(); in the handleSubmit() handler function.
The browser page was reloading when the submit button was clicked, causing the request to be canceled before completing.
Perhaps the window is being refreshed. Maybe forgot to prevent default behavior.
I was getting the same error when I was (purposely) refreshing a page for testing purposes. I removed the
window.location.reload(); command
and the proxy error disappeared.
just re-render the react component instead.
Project works as intended locally. To run locally, I currently run the command npm run start in both the project root and the client root concurrently.
I am working to create a simple application using Express and Create React App. Despite a successful build and no errors in my Heroku logs, my deploy shows a blank page that says "Not Found" and has a 404 error in the chrome console.
File directory:
client
> src
-> components
-> app.js
> package.json
routes
> tweets.js
index.js
package.json
Root package.json:
{
"name": "newStock",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"npm": "6.x",
"node": "12.x"
},
"scripts": {
"start": "node index.js",
"heroku-postbuild": "cd client && npm install && npm run build",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"password-generator": "^2.2.3",
"socket.io": "^2.3.0",
"socket.io-client": "^2.3.0",
"twitter": "^1.7.1"
}
}
Root index.js:
const express = require("express");
const http = require("http");
const socketio = require("socket.io");
const path = require("path");
const bodyParser = require("body-parser");
const app = express();
require("dotenv").config({ path: "./.env" });
require("./routes/tweets.js")(app, io);
const server = http.createServer(app);
const io = socketio(server);
//middleware
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "client/build")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/client/build/index.html"));
});
const port = process.env.PORT || 3001;
console.log(`Password generator listening on ${port}`);
server.listen(port, () => {
console.log("server is up");
});
Root routes/tweets.js:
const Twitter = require("twitter");
module.exports = (app, io) => {
let twitter = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});
let socketConnection;
let twitterStream;
app.locals.searchTerm = "cake"; //Default search term for twitter stream.
app.locals.showRetweets = false; //Default
/**
* Resumes twitter stream.
*/
const stream = () => {
console.log("Resuming for " + app.locals.searchTerm);
twitter.stream(
"statuses/filter",
{ track: app.locals.searchTerm },
stream => {
stream.on("data", tweet => {
sendMessage(tweet);
});
stream.on("error", error => {
console.log(error);
});
twitterStream = stream;
}
);
};
/**
* Sets search term for twitter stream.
*/
app.post("/setSearchTerm", (req, res) => {
let term = req.body.term;
app.locals.searchTerm = term;
twitterStream.destroy();
stream();
console.log(req.body.term);
});
/**
* Pauses the twitter stream.
*/
app.post("/pause", (req, res) => {
console.log("Pause");
console.log(req.body.term);
twitterStream.destroy();
});
/**
* Resumes the twitter stream.
*/
app.post("/resume", (req, res) => {
console.log(req.body.term);
console.log("Resume");
stream();
});
//Establishes socket connection.
io.on("connection", socket => {
socketConnection = socket;
stream();
socket.on("connection", () => console.log("Client connected"));
socket.on("disconnect", () => console.log("Client disconnected"));
});
/**
* Emits data from stream.
* #param {String} msg
*/
const sendMessage = msg => {
if (msg.text.includes("RT")) {
return;
}
socketConnection.emit("tweets", msg);
};
};
All I needed to do was reset the git cache of my client directory as it wasn't even being added to git because of this. I only noticed when I uploaded the repo to GitHub to save it for another day.
wow.