【发布时间】:2020-05-13 03:59:06
【问题描述】:
我正在做一个项目,使用 React JS 作为前端,Node&Express 作为后端。
我正在本地开发环境和真实服务器中测试 React 和 Node 之间的连接。
我使用 AWS EC2 作为服务器。
问题是
1) 本地前端 (localhost:3000) 本地后端 (localhost:3001) (完美运行)
2) 本地前端 (localhost:3000) AWS 后端 (13.209.70.185:3001)(也可以)
3) AWS Front (13.209.70.185:80) AWS Back (13.209.70.185:3001)(它不起作用!!!)
我可以在浏览器控制台中看到这样的错误消息。
'SyntaxError: Unexpected token
我检查了这3个案例,但我找不到这个问题的解决方案。
我在 Stack Overflow 和开发社区中尝试了所有类似的解决方案,但由于我缺乏
知识,我终于请你们帮我解决这个问题。
这里有一些参考来诊断我的问题。
- AWS 网络安全设置
- 反应代码
使用 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',
}
}));
}
- 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;
- 此项目的简化架构
【问题讨论】:
-
也许更多信息会更好:-您的后端应用程序中是否有任何日志?http 调用的状态或响应是什么?通常,您收到的错误消息是收到 HTML 而不是 json。所以最好检查一下http调用错误信息是什么
-
@Ay_mhwan 我不知道为什么 http-proxy-middleware 不起作用,但我解决了使用 process.env.NODE_ENV 变量来更改两个不同的地址。谢谢!
标签: node.js reactjs amazon-web-services amazon-ec2 server