MERN Stack - 在同一个端口上表达和反应? [英] MERN Stack - Express and React on same port?

查看:52
本文介绍了MERN Stack - 在同一个端口上表达和反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个使用 MERN(MongoDB、Express、React、Node)堆栈的项目,在将数据从 React 组件内的表单发布到 Node.js 中定义的 API 端点时遇到问题.当我提交表单时,浏览器只显示无法发布错误.我非常有信心,如果我在 React 中为表单提交创建一个事件处理程序并使用 Axios 等库处理 POST,我可以解决这个问题.

I'm working on a project with the MERN (MongoDB, Express, React, Node) stack and I'm having issues when posting data from a form within a React component to an API endpoint defined in Node.js. When I submit the form the browser just shows a CANNOT POST error. I'm pretty confident that if I create an event handler for the form submit within React and handle the POST using a library such as Axios that I could get around this issue.

但最终我认为这个问题是因为 Node 后端运行在与 React 前端不同的端口上.有没有一种方法可以配置我的堆栈,以便我可以使用标准形式的 POST 并可能让 FE 和 BE 在同一端口上运行?

But ultimately I believe this problem is because the Node backend is running on a different port to the React front end. Is there a way that I can configure my stack so I can use a standard form POST and potentially have the FE and BE running on the same port?

推荐答案

我看到您正在运行一个未弹出的 CRA.这意味着当您从 create-react-app 文件夹运行 npm run start 时,您应该在端口 3000(默认端口)上运行 react.

I see that you are running an un-ejected CRA. That means that when you run npm run start from your create-react-app folder you should have react running on port 3000, the default port.

首先,我建议将您的服务器和客户端代码保存在一个单独的文件夹中,并使用单独的 package.json 文件

First I would recommend keeping your server and client code into a separate folder with separate package.json files

现在假设您在 /server/index.js 中有此代码,它直接来自于 express 示例,但路由以 /api 开头,并且还将继续运行端口 5000.这非常重要,一分钟后您就会明白为什么.

Now let suppose you have this code in /server/index.js Its straight out of the express example but the route starts with /api and also will run on port 5000. This is very important and you will see why in a minute.

const express = require('express');
const app = express();

app.get('/api/hello', (req, res) => res.send('Hello World!'))

app.listen(5000, () => console.log('Example app listening on port 5000!'))

现在回到你的 /client 文件夹,我将假设你的 CRA 在那里,打开 package.json 并添加以下行:

Now back into your /client folder where I will assume your CRA is, open package.json and add the following lines:

"proxy": {
  "/api/*": {
    "target": "http://localhost:5000"
  }
},

现在尝试使用 axios 来调用服务器,例如:

Try now to do a call the server from react with axios for example:

const helloFromApi = 
  axios
    .get('/api/hello')
    .then(res => res.data);

希望能帮到你

更新 10/21/2019

package.json 中的proxy 字段必须是字符串

proxy field in package.json must be a string

"proxy": "http://localhost:5000"

这篇关于MERN Stack - 在同一个端口上表达和反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆