我正在尝试使用以下代码从我的 React 应用程序进行后期调用。
writeToFile = (data = {}) => {
let url = "http://localhost:8000/write";
console.log(data);
return fetch(url, {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({"content": "some content"})
}).then(res=>res.json())
.then(res => console.log(res));
}
但是,它给了我下面给出的错误:
同样的请求在邮递员(API 测试应用程序)中起作用。这是一个application/json
类型的请求,期望得到相同类型的响应。
编辑1:
在同一个应用程序GET
请求(下面的代码)工作正常:
readFromFile = () => {
fetch('http://localhost:8000/read')
.then(function(response) {
return response.json();
})
.then((myJson) => {
console.log(myJson.content);
this.setState({messages: this.state.messages.concat({content: myJson.content, type: 'received'})});
console.log(this.state.messages);
});
}
相关服务端代码:
function writeToFile(request, response) {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
// const dataToWrite = JSON.parse(body)["content"];
// console.log(dataToWrite);
myFileModule.fileWriter(JSON.parse(body)["content"]);
response = allowCORS(response);
response.writeHead(200, {'Content-Type': 'application/json'});
response.write(JSON.stringify({ content: "success..." }));
response.end();
});
}
function postRequestHandler(request, response) {
var path = url.parse(request.url).pathname;
switch (path) {
case '/write':
writeToFile(request, response);
break;
default:
response = allowCORS(response);
response.writeHead(404, {'Content-Type': 'application/json'});
response.write(JSON.stringify({ content: "Path not defined" }));
response.end();
break;
}
}
function allowCORS(response) {
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed
response.setHeader('Access-Control-Allow-Credentials', true); // If needed
return response;
}