Dillanm
Dillanm

Reputation: 866

node express no data getting to server

Have looked for similar questions and can't find anything on this, so apologies if it already exists.

I'm pretty new to front-end work so I've got a fairly simple personal project on the go. I've got a pretty basic node/express setup and am trying to initiate a GET request to the /next-user URL

the GET is set up in the server as:

app.get('/next-user', function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    console.log(req.body)
})

I know a common issue with this is that the body-parser module is not setup, so here is my setup code:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));

and the request is setup like;

    var data = {name:"HelloServerWorld"};
    console.log(data)
    $.getJSON("http://localhost:8081/next-user", data, function(response){
        console.log(response);
    });

The server always echos an empty JSON object regardless of what I send to it where the client can see that the object is populated. I didn't want to post the entirety of the code but if it's needed then let me know, but I'm fairly confident the problem lies in what I've given so far, I'm just not sure where

Upvotes: 0

Views: 54

Answers (2)

CFrei
CFrei

Reputation: 3627

Replace console.log with res.end and you should get back the request.

Upvotes: 0

hellojebus
hellojebus

Reputation: 3583

GET requests don't include "req.body", req.body is used with POST requests. You may want to pass data in the form of a parameter, e.g. " "/next-user/:id" or using a POST request instead to pass over the data!

Upvotes: 1

Related Questions