Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass JSON object to node.js server

I have a test JSON object as follows

{ Id: 100, plugins: [{ Name: 'Test', Version: '2' }] }

which I created using

var json = {}; 
json.Id =  100;
var plugins = [];
json.plugins = plugins;
json.plugins.push({"Name" : "Test", "Version" : "2"});

I have a client side function making an AJAX post request as follows

function postJSON() {
    $.ajax({
      type: 'POST',
      url: 'features',
      data: json,
      dataType: 'json'
    });
  }

I am trying to read this information on my server by just typing console.log(req) for now but it does't seem to be getting my json object.

app.post("/features", function(req, res) {
    console.log(req);
})

Thanks for help!

like image 969
dopplesoldner Avatar asked Jul 02 '13 15:07

dopplesoldner


People also ask

How do you send and receive JSON data to and from the server in node JS?

Import the HTTP module with require keyword at the top of the app. js file, and store that returned result in a const variable. Now call the createServer() function, it will provide you a web server in return. Later this server object will be used to listen the connection on a specified host and port.

How do I fetch JSON data from a server with node js?

Replicating fetch() with 'node-fetch' package To install, run npm install node-fetch , and set up your code like this: const fetch = require('node-fetch'); let url = "https://www.reddit.com/r/popular.json"; let settings = { method: "Get" }; fetch(url, settings) . then(res => res.

How do I send and receive JSON data from server?

Use JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET, or POST method by assigning the JSON string to a variable.


1 Answers

As long as you have the bodyParser() middleware installed, Express should parse the JSON request payload into req.body.

like image 150
SLaks Avatar answered Sep 29 '22 14:09

SLaks