0

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\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");
});
JDorman
  • 89
  • 1
  • 12
  • try to remove the dot in your route and lets only `/postjson`..and did you tried post it by postman? – BrTkCa Dec 11 '17 at 14:18

2 Answers2

0

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

Galupuf
  • 2,827
  • 1
  • 12
  • 29
  • Did you change your axios request to axios.post("http://localhost:3000/postJson/", {postJsonData})? Make sure to have "http://" before localhost – Galupuf Dec 11 '17 at 15:37
0

Turns out both react and my node server were running on localhost:3000 simultaneously which is apparently not okay.

Running my node server on localhost:3001 from a new command line window allowed me to do both at the same time.

Not sure how this would work when making a production build though.

JDorman
  • 89
  • 1
  • 12