【发布时间】:2019-03-01 08:17:04
【问题描述】:
我有一个运行 React 的前端。这是我调用 API 的代码
componentDidMount(){
const jso = JSON.stringify({
username: 'admin@etsmtl.ca',
password: 'admin'
})
fetch("https://desolate-escarpment-15258.herokuapp.com/authentication", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: jso,
}).then(res => res.json()).then((result) => {
this.setState({
answer: result.answer
})
}, (error) => {
this.setState({isLoaded: true, error});
})
}
现在这是来自 nodeJS 服务器的代码
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser')
//setting port
var port = process.env.PORT || 5000
//helps node to pasre JSON
app.use(bodyParser.json());
//Enabeling all Access-Control-Allow-Origin
app.use(cors());
app.get('/', function(req, res){
res.send({answer: "hello world!"});
})
app.post('/authentication', function(req, res){
console.log(req.body);
res.send({answer: req.body});
})
app.listen(port, function(){
console.log("app running");
})
问题:nodeJS 无法处理来自 React 的请求。
我现在两台服务器之间的连接工作正常,因为当我在 nodeJS 中执行 res.send("hello Wolrd"); 时我可以收到答案
仅供参考,nodeJS 由 heroku 托管,reactJS 由 AWS S3 托管。但是我们在本地尝试过,但都没有成功
【问题讨论】:
-
你试过
res.send(200, {answer: req.body})吗? -
是抛出错误信息还是什么?还是根本没有输出?到底发生了什么?
-
另外你正在做
(error) => { this.setState({isLoaded: true, error}); }),error的状态有什么设置吗? -
当我执行以下命令时:
curl --request POST --data "username=admin" https://desolate-escarpment-15258.herokuapp.com/authentication我收到这个:{"answer":{}} -
这是一个好兆头。至少在respnse中有一个answer属性。执行
curl --header "Content-Type: application/json" \ --request POST \ --data '{"username":"admin@etsmtl.ca","password":"admin"}' \ https://desolate-escarpment-15258.herokuapp.com/authentication时返回什么?
标签: javascript node.js reactjs heroku amazon-s3