I have created a front end app by creat-react-app .
The command " npm run start " can create a webpack-dev-server and serve my
front end app for developing. Here is the problem comes:
How can I gracefully start my developing story from those problems !
There are two ways to solve cross-origin problems in node server,
First install cors module. npm install cors
and then use it inside your app
const Express = require("express");
const BodyParser = require("body-parser");
const Cors = require("cors");
const app = Express();
app.use(Cors());
app.use(BodyParser.urlencoded({ extended: false }));
app.use(BodyParser.json());
app.listen(3001, 'localhost', (err) => {
if(err) {
console.log(err);
process.exit(-1);
}
console.log("Server listen port 8083");
});
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
next();
});
An easy way to deal with CORS with a NodeJS backend is to use ExpressJS middleware and the "cors" extension, as detailed in the ExpressJS documentation:
For testing purposes there are various browser extensions that implement CORS headers in all your requests automatically (Access-Control-Allow-Origin, Access-Control-Allow-Methods , Access-Control-Allow-Headers). Using this extension makes all your request from the browser CORS enabled (NOT GOOD FOR PRODUCTION, JUST FOR TEST/DEV).
Note that the so called "simple requests", ones using only GET / HEAD / POST and the following content types: application/x-www-form-urlencoded, multipart/form-data, text/plain do not trigger a CORS preflight request so they are allowed.
For a general understanding of CORS i would refer to the Mozilla MDN docs:
The easiest way to overcome CORS issues is to use npm module for cors. Install it in your project using:
npm i cors
Then include it in your app.js file like this:
const cors = require('cors');
and then use it as a middleware in your app.js like this:
app.use(cors());
And this should do! Hope this helps!!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.