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

    评论

报告相同问题?