localhost:3000 - 反应客户端
localhost:8080 - NodeJS 服务器
我编写了以下类来调用服务器 API 方法:
import React, { Component } from 'react';
class Server {
static call(apiMethod, params = {}, httpMethod = 'POST') {
return fetch('http://localhost:8080/' + apiMethod, {
mode: 'no-cors',
method: httpMethod,
body: params
});
}
}
export default Server;
我正在尝试使用它:
process() {
let method = this.state.mode;
Server.call(method, {
name: this.state.user,
password: this.state.password
}).then(function(response) {
console.log(response);
}).then(function(data) {
console.log(data);
});
}
我不明白这是什么问题?如何从服务器获得响应?

Then回报Promise。当收到响应时,它会发送给第一个then带有response. 您已经response可以使用其中一种方法从中获取响应主体。这些方法还返回
Promisea 将被处理成thenorcatch。那些。该功能应该是这个样子总的来说,我们设法弄清楚了。感谢@Sapphiron 的帮助。
整个问题原来是 CORS 和服务器标头。为了让一切正常工作,我更正了服务器上的代码(NodeJS + Express),如下所示:
以及客户端上的代码:
现在一切正常 =)