简体   繁体   English

如何使前端应用程序访问节点服务器api

[英]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: 问题来了:

  1. My front end app must request some api from a node server I had created before. 我的前端应用程序必须从我之前创建的节点服务器中请求一些api
  2. By default create-react-app start a webpack-dev-server on port 3000 默认情况下,create-react-app在端口3000上启动webpack-dev-server
  3. My node server was started on port 3001 我的节点服务器在端口3001上启动
  4. Access port 3001 directly may cause cross-origin problems 直接访问端口3001可能会导致跨域问题

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 使用cors节点模块

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");
});
  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: 使用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文档:

Mozilla MDN CORS guide Mozilla MDN CORS指南

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.

相关问题 如何从节点/ Express服务器提供Vuejs前端文件? - How can I serve my Vuejs front end files from my node/express server? 如何将新的 React JS 前端嵌入到我现有的单体 Node JS 应用程序中? - How can I embed new React JS Front-end in my existing monolithic Node JS App? 如何将 Heroku 生成的服务器端口应用到我的前端 Vue.js 应用程序? - How can I apply the Heroku generated server port to my front-end Vue.js app? 如何使用 Node.js 服务器将我的图像数据从前端保存到 Mongoose 数据库 - How can I save my image data from front end to Mongoose database using Node.js server 如何将查询参数从我的前端服务传递到我的服务器? - How can I pass a query param from my service on the front end to my server? 如何在服务器的控制台中访问我的nodeJS应用程序? - How can I access to my nodeJS app in console on my server? 我怎样才能等待我的“请求”和响应回到前端? - How can I wait for my "request" and response back to front end? 节点JS | 英雄联盟 | MongoDB 地图集 | 如何确保只有我的应用程序可以访问我的后端? - Node JS | Heroku | MongoDB Atlas | How do I make sure only my app can access my backend? 如何在我的应用程序中限制对 API 子集的访问? - How can I restrict access to a subset of APIs in my application? 如何将离子应用程序连接到cpanel节点服务器? - How can I connect my ionic app to cpanel node server?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM