[英]How can I make my front end app access my node server apis
I have created a front end app by creat-react-app . 我已经通过creat-react-app创建了一个前端应用程序 。
The command " npm run start " can create a webpack-dev-server and serve my 命令“ npm run start ”可以创建一个webpack-dev-server并为我的
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. 首先安装cors模块。 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: 使用NodeJS后端处理CORS的一种简单方法是使用ExpressJS中间件和“ cors”扩展,如ExpressJS文档中所述:
ExpressJS CORS guide ExpressJS CORS指南
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). 为了进行测试,有各种浏览器扩展会自动在所有请求中实现CORS标头(Access-Control-Allow-Origin,Access-Control-Allow-Methods和Access-Control-Allow-Header)。 Using this extension makes all your request from the browser CORS enabled (NOT GOOD FOR PRODUCTION, JUST FOR TEST/DEV). 使用此扩展程序将使您从浏览器发出的所有请求都变为启用CORS(不适用于生产,仅用于测试/开发)。
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. 请注意,所谓的“简单请求”(仅使用GET / HEAD / POST和以下内容类型的请求):application / x-www-form-urlencoded,multipart / form-data,text / plain不会触发CORS预检请求所以他们被允许。
For a general understanding of CORS i would refer to the Mozilla MDN docs: 对于CORS的一般理解,我可以参考Mozilla MDN文档:
The easiest way to overcome CORS issues is to use npm module for cors. 解决CORS问题的最简单方法是对cors使用npm模块。 Install it in your project using: 使用以下命令将其安装在您的项目中:
npm i cors
Then include it in your app.js file like this: 然后将其包含在您的app.js文件中,如下所示:
const cors = require('cors');
and then use it as a middleware in your app.js like this: 然后将其用作app.js中的中间件,如下所示:
app.use(cors());
And this should do! 这应该做! Hope this helps!! 希望这可以帮助!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.