在同一台服务器上托管React和Express?

5

我正在开发一个具有联系页面的React网站。在联系页面上,有一个文本字段,您可以在其中输入消息,该消息将发送到特定的电子邮件地址。

现在我只是想在我的React应用程序中设置Express,唯一需要Express的是这个功能。

在我的React应用程序中,我正在执行以下操作:

$.post('http://localhost:3030/API',{value:'hi'}, function(result) {
  console.log(result);
});

在我的Express index.js 文件中,我正在做以下操作

app.get('/API', (request, response) => {  
  console.log(request);
})

这只是为了简单测试一下是否正常工作。

当我运行这两个并尝试执行我的 post 函数时,我会收到“No 'Access-Control-Allow-Origin' header is present on the requested resource.”错误消息,这基本上是说我不能向另一个域名发出请求。问题不在于这个错误,而在于我正在两个不同的服务器上运行我的 Express 服务器和 React 应用程序。

有没有办法让它们在同一个服务器上运行呢?我非常新手后端开发,请帮帮我!


1
这并不是很难,只需要让你的Express应用程序为React应用程序提供HTML即可。 - James
2个回答

3
是的,React运行在客户端,Express是一个Node.js框架。如果你正在运行任何样板文件,那么你很有可能正在使用Express。
下面是关于更完整路由的详细步骤: https://medium.com/@patriciolpezjuri/using-create-react-app-with-react-router-express-js-8fa658bf892d 在我的几个应用程序中,我的路由看起来像这样:
//router.js--and I'm positive this is from some react-express boilerplate
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

const react =  (req, res, next)=>{
  res.render('react', { 
    title: 'React Application',
    layout: false
  });
};

router.get('/app', react);
router.get('/app*', react);
module.exports = router;

//app.js
...
app.use('/', routes); //<--this is the exported router. 
...

如果您想更简单地理解,可能类似于以下内容:

   let reactRoute = (request, response, next) => {
     //render your react page however you're doing that. 
   }
   express.use('/API', yourApiFunction)
   express.use('/', reactRoute)
   express.use('/*', reactRoute) //Wildcards are REALLY important if you're routing inside react.

你也可以通过代理来绕过某些事情,但这往往会比你想象的更加复杂。此外,请记住,如果你对Node后端不熟悉,你并不一定非要使用它。React是客户端的,我将其与一些生产.NET应用程序、一些PHP(天哪!)以及许多Node服务器一起使用。


-1

解决 No 'Access-Control-Allow-Origin' header is present on the requested resource. 需要使用 cors 中间件

在终端输入 yarn add cors 或者 npm i cors

server.js 文件中添加

const cors = require("cors");
const express = require("express");
const app = express();

app.use(cors());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接