简体   繁体   中英

How can I make my front end app access my node server apis

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:

  1. My front end app must request some api from a node server I had created before.
  2. By default create-react-app start a webpack-dev-server on port 3000
  3. My node server was started on port 3001
  4. Access port 3001 directly may cause cross-origin problems

How can I gracefully start my developing story from those problems !

There are two ways to solve cross-origin problems in node server,

  1. Using cors node module

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");
});
  1. simply use following headers
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:

ExpressJS CORS guide

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:

Mozilla MDN CORS guide

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM