首页 > 解决方案 > 在 AWS 中使用 Node js 做出反应。React 和 Node 问题之间的连接

问题描述

我正在做一个项目,其中 React JS 作为前端,Node&Express 作为后端。

我正在本地开发环境和真实服务器中测试 React 和 Node 之间的连接。

我使用 AWS EC2 作为服务器。


问题是

1) 本地前 (localhost:3000) <-> 本地后 (localhost:3001) (完美工作)

2) 本地前端 (localhost:3000) <-> AWS 后端 (13.209.70.185:3001) (也可以)

3) AWS 前 (13.209.70.185:80) <-> AWS 后 (13.209.70.185:3001)不起作用!!!


我可以在浏览器控制台中看到这样的错误消息。

'SyntaxError: 位置 0 处 JSON 中的意外标记 <'

在此处输入图像描述

我检查了这 3 个案例,但我找不到这个问题的解决方案。

我在 Stack Overflow 和 dev Communities 中尝试了所有类似的解决方案,但由于我缺乏

知识,我终于请你们帮我解决这个问题。



这是诊断我的问题的一些参考。

  1. AWS 网络安全设置

我使用端口 3001 作为 Node js 服务器。

  1. 反应代码

使用 http-proxy-middleware,我将请求发送到服务器 (13.209.70.185:3001)

但是如果请求来自“localhost:3000”(这是本地反应),我将发送到“localhost:3001”。(本地节点服务器)

/* setupProxy.js*/
const proxy = require("http-proxy-middleware");

module.exports = function (app) {

    app.use(proxy("/api", {
        target: "http://13.209.70.185:3001", 
        changeOrigin:true,
        ws: true,
        router: {
            'localhost:3000': 'http://localhost:3001',
        }
    }));

}
  1. NodeJS 代码
/// app.js ///
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();

// view engine setup
app.use(cors());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api', (req, res) => res.json({username: 'Daniel'}));


// catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   next(createError(404));
// });

// error handler
// app.use(function(err, req, res, next) {
//   // set locals, only providing error in development
//   res.locals.message = err.message;
//   res.locals.error = req.app.get('env') === 'development' ? err : {};

//   // render the error page
//   res.status(err.status || 500);
//   res.render('error');
// });

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

var port = normalizePort(process.env.PORT || '3001');
app.set('port', port);


app.listen(port, "0.0.0.0");

module.exports = app;
  1. 该项目的简化架构

在此处输入图像描述

标签: node.jsreactjsamazon-web-servicesamazon-ec2server

解决方案


试试这哥们..

在您的本地环境中,react 应用程序的端口是,:3000但在 AWS 中它托管在,:80因此setupProxy.js替换localhost:30000.0.0.0:80localhost:30010.0.0.0:3001

您需要替换localhost0.0.0.0以确保“侦听每个可用的网络接口”发生。


推荐阅读