【发布时间】:2017-12-11 14:13:41
【问题描述】:
继续这个问题:Axios can GET but not POST to the same URL
我已经尝试解决这个问题太久了。
我想从我的 React 应用 POST 到 .JSON 文件。谁能告诉我我做错了什么?
我使用 axios 的 AJAX POST 函数总是返回 404。我正在节点服务器上监听它,但 app.post 永远不会触发。
谢谢。
来自我的 React 应用的 POST 请求:
postJson = (postJsonData) => {
axios.post('./postJson/', {
postJsonData
})
.then(function (response) {
console.log("success!");
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
app.js(节点服务器):
/*========== Default Setup for node server copied from node website ==========*/
const http = require('http');
const hostname = '127.0.0.1';
const port = 3001;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
/*========== Listen for POST (Trying to get the data from my REACT app
- will then assign it to "obj" below) ==========*/
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.post("./postJson/", function(request, response) {
console.log("MURRRR");
console.log(request.body); //This prints the JSON document received (if it is a JSON document)
/*=== JSON Stuff ===*/
var jsonfile = require('jsonfile')
var file = './scene-setup.json'
var obj = {name: 'JP'}
jsonfile.writeFile(file, obj, function (err) {
console.error(err)
})
});
//Start the server and make it listen for connections on port 3000
app.listen(3000, function(){
console.log("server is listening to 3000");
});
【问题讨论】:
-
尝试删除路线中的点,只允许
/postjson..您是否尝试过由邮递员发布?