我目前正在尝试在AWS EC2实例上运行MERN堆栈应用程序。我在应用程序中使用端口3000,在api中使用端口5000(代理)。
该应用程序运行find并且我现在仅使用npm run dev来启动服务器,因为这是处于开发的非常早期的阶段,我们只需要一个有效的示例。
我的问题是LogIn.js(使用jwt令牌验证方法)。 API端点在本地工作,但控制台在服务器上显示:
POST http://52.50.117.51:5000/api/user/Login网:: ERR_CONNECTION_REFUSED 提取失败,加载:POST“ http://52.50.117.51:5000/api/user/Login”。
在运行'npm run dev'时显示呼叫时,此err拒绝连接,因为看起来端口已在使用中。然后,我阅读了有关反向代理的信息,并在重启nginx之后尝试更改我的nginx网站可用文件:
server {
listen 80 default_server;
server_name _;
location / {
proxy_cache_bypass $http_upgrade;
}
location /api/ {
proxy_pass http://localhost:5000/;
}
}
我也遇到了一个CORS错误,我设法解决了该错误,重新启动nginx之后,我可以登录了!但只有一次。
(root)index.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
const cors = require('cors');
const path = require('path')
// INITIALIZE THE APP
const app = express();
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || `mongodb://localhost:27017/node-react-
starter`);
// IMPORT MODELS
require('./models/Room');
require('./models/Building');
// BODYPARSER MIDDLEWARE
app.use(bodyParser.json());
// CORS MIDDLEWARE
app.use(cors())
// COOKIEPARSER MODULE
app.use(cookieParser())
//IMPORT ROUTES
const userRoutes = require("./routes/userRoutes");
app.use("/api/user", userRoutes)
require('./routes/roomRoutes')(app);
require('./routes/buildingRoutes')(app);
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
const path = require('path');
app.get('*', (req,res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`app running on port ${PORT}`)
});
/client/src/setupProxy.js
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
app.use(proxy('/api/*', { target: 'http://localhost:5000' }))
}
/client/src/components/LogIn.js
import React, {useState} from 'react';
const LogIn = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = event => {
event.preventDefault()
const requestBody = {
"email": email,
"password": password
}
console.log(JSON.stringify(requestBody))
fetch('http://52.50.117.51:5000/api/user/Login',{
method: 'POST',
xhrFields: { withCredentials: true },
body: JSON.stringify(requestBody),
headers: {"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"}
})
.then(function(response){
//alert(response.json());
// resolve(response ? JSON.parse(response) : {})
return response.json()
}).then(function(body){
console.log(body.message);
if (body.message == 'Auth successful') {
localStorage.setItem("token", body.token);
}
window.location = '/';
})
}
return (
<div className="login-page">
<div className="login-card">
<form onSubmit={handleSubmit}>
<h2>Log in</h2>
<div>
<label>Email</label>
<input
type='text'
name='email'
placeholder='email'
value={email}
onChange={ (e) => setEmail(e.target.value) }
/><br/>
</div>
<label>Password</label>
<input
type='password'
name='password'
placeholder='Password'
value={password}
onChange={ (e) => setPassword(e.target.value) }
/><br/>
<input type='submit' value='Log In'/>
</form>
</div>
</div>
)
}
export default LogIn;
服务器是运行ubuntu的t2.micro服务器,我更改了安全组,以允许端口5000和3000(以及80,443,22)
非常感谢!
答案 0 :(得分:-1)
验证 52.50.117.51
是否是您的公共 IP。
您不需要使用单独的 http-proxy-middleware
,您已经在侦听端口 5000