weixin_33717298 2017-12-11 14:13 采纳率: 0%
浏览 88

Node.js + React:如何发布

Follow on from this question: Axios can GET but not POST to the same URL

I've been trying to figure this out for too long now.

I want to POST from my React app to a .JSON file. Can anyone tell me what I'm doing wrong?

My AJAX POST function using axios always returns a 404. I'm listening for it on the node server but app.post never fires.

Thanks.

POST request from my React app:

postJson = (postJsonData) => {
        axios.post('./postJson/', {
            postJsonData
        })
        .then(function (response) {
            console.log("success!");
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
     }

app.js (node server):

/*========== 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
');
});

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");
});
  • 写回答

2条回答 默认 最新

  • weixin_33719619 2017-12-11 14:20
    关注

    Two things I noticed:

    Your post endpoint doesn't need a leading "." I would make it just "/postJson"

    Make sure you are posting to "http://localhost:3000/postJson"

    Make sure you have the network tab open to see the actual URL you are requesting to.

    Cheers

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器