我正在尝试通过Nginx从我的React前端向我的节点js后端发起请求。我已经尝试了将近20种不同的Nginx配置,但仍然遇到502错误。
我的前端代码:
import logo from './logo.svg';
import './App.css';
class App extends Component {
state = {
response: '',
post: '',
responseToPost: '',
};
componentDidMount() {
this.callApi()
.then(res => this.setState({ response: res.express }))
.catch(err => console.log(err));
}
callApi = async () => {
const response = await fetch('/api/hello');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
};
handleSubmit = async e => {
e.preventDefault();
const response = await fetch('/api/world', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ post: this.state.post }),
});
const body = await response.text();
this.setState({ responseToPost: body });
};
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
<p>{this.state.response}</p>
<form onSubmit={this.handleSubmit}>
<p>
<strong>Post to Server:</strong>
</p>
<input
type="text"
value={this.state.post}
onChange={e => this.setState({ post: e.target.value })}
/>
<button type="submit">Submit</button>
</form>
<p>{this.state.responseToPost}</p>
</div>
);
}
}
export default App;
我的后端代码:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
// API calls
app.get('/api/hello', (req, res) => {
res.send({ express: 'Hello From Express' });
console.log(req.originalUrl);
});
app.post('/api/world', (req, res) => {
console.log(req.body);
console.log(req.originalUrl);
res.send(
`I received your POST request. This is what you sent me: ${req.body.post}`,
);
});
// Serve any static files
app.use(express.static(path.join(__dirname, '/home/matan/frontend/build')));
// Handle React routing, return all requests to React app
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '/home/matan/frontend/build', 'index.html'));
});
app.listen(port, () => console.log(`Listening on port ${port}`));
Nginx配置:
server {
listen 80 default_server;
listen [::]:80 default_server;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name moneyserver;
location / {
# This would be the directory where your React app's static files a$
root /home/matan/frontend/build;
try_files $uri /index.html;
error_page 405 =200 $uri;
}
location /api {
proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
Netstat信息
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 6673/nginx: master
tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN 730/systemd-resolve
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 3202/sshd
tcp6 0 0 :::80 :::* LISTEN 6673/nginx: master
tcp6 0 0 :::22 :::* LISTEN 3202/sshd
我试图将Nginx的默认80端口更改为5000,但它一直发送到端口80
修改:
我设法将端口更改为5000,但仍然得到502错误提示
我想我几乎阅读了所有可能的教程,但是仍然无法从这些http请求中获得响应。当我尝试不使用/ api发送请求时,我得到的是HTML响应,我认为它是前端代码,无法获得所需的响应。
谢谢!
答案 0 :(得分:0)
也尝试代理传递http://localhost:5000/api
,而不是同时在nginx和node js上保持静态构建,而尝试仅在nginx上保持构建。
答案 1 :(得分:0)
将proxy_pass http://127.0.0.1:5000;更改为proxy_pass http://127.0.0.1:5000/api; 然后重启nginx