【问题标题】:Node.js + React: How to POSTNode.js + React:如何发布
【发布时间】: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..您是否尝试过由邮递员发布?

标签: node.js ajax reactjs post


【解决方案1】:

我注意到两件事:

您的帖子端点不需要前导“。”我会把它变成“/postJson”

确保您发布到“http://localhost:3000/postJson

确保您已打开网络选项卡以查看您请求的实际 URL。

干杯

【讨论】:

  • 您是否将您的 axios 请求更改为 axios.post("localhost:3000/postJson", {postJsonData})?确保在 localhost 之前有“http://”
【解决方案2】:

结果是 react 和我的节点服务器同时在 localhost:3000 上运行,这显然是不行的。

从新的命令行窗口在 localhost:3001 上运行我的节点服务器允许我同时执行这两项操作。

但不确定在进行生产构建时这将如何工作。

【讨论】:

    猜你喜欢
    • 2015-04-08
    • 2021-01-04
    • 2020-12-25
    • 2023-03-15
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    相关资源
    最近更新 更多