Node.js how to read json data from request? - json

I have a server as following:
app.post('/', function(req, res, next) {
console.log(req);
res.json({ message: 'pppppppppppppssssssssssssss ' });
});
The request is sent from a client as:
$.ajax({
type: "POST",
url: self.serverURI,
data: JSON.stringify({ "a": "128", "b": "7" }),
dataType: 'json',
success: function (result) {
console.log(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
so far the connection fine.
My problem is in the server:
console.log(req);
where I want to read the data I sent. How can I read { "a": "128", "b": "7" } from req?

Although you're not mentioning it, your code looks like it's written for an Express environment. My answer is targeted to this.
Make sure to use body-parser for Express. In case, your project depends on some generated boilerplate code, it's most likely already included in your main server script. If not:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
Installation with npm: npm install body-parser --save
The parsed JSON can then be accessed through req.body:
app.post('/', function(req, res, next) {
console.log(req.body); // not a string, but your parsed JSON data
console.log(req.body.a); // etc.
// ...
});

For Express 4+,
const express = require("express");
const app = express();
app.use(express.json());
Then, you can use req.body as expected.
app.post("/api", (req, res) => {
/*
If the post request included { data: "foo" },
then you would access `data` like so:
*/
req.body.data
...
});

Related

Node.js HTML response body

I am using the below code to post some JSON data to a url and in response I am getting a HTML page.
var request = require('request');
request.post({
url: "URL OF A WEBSITE",
headers: {
"Content-Type": "application/json"
},
body: {
my_json_obj
},
json:true
}, function(error, response, body){
console.log(error);
console.log(JSON.stringify(response));
console.log(body);
});
This code works fine I am getting a HTML page in the body tag.
I want to load that HTML page in the browser. How should I do that, I know this is a very basic question but I am very new to node.js someone please help me?
Follow the Express "Hello World" example and use your request call in the route handler:
/*jslint node:true, esversion:6*/
"use strict";
const request = require("request"),
express = require("express"),
app = express();
let my_json_obj = {},
URL_OF_WEBSITE = "http://www.google.com";
app.get("/", function (req, res) {
request.post({
url: URL_OF_WEBSITE,
headers: {
"Content-Type": "application/json"
},
body: {
my_json_obj
},
json: true
}, function (error, response, body) {
if (error) {
console.log(error);
return res.sendStatus(404);
}
console.log(JSON.stringify(response));
console.log(body);
res.send(body);
});
});
app.listen(3000, function () {
console.log("Example app listening on port 3000!");
});
node.js does have its own way to make a server, but for the sake of brevity and ease I just recommend using Express.
Are you using Express js? It would make things a lot easier when working with Node js apps.
Look into Express routing:
https://medium.com/javascript-scene/introduction-to-node-express-90c431f9e6fd
You can create an Express boilerplate in the terminal by using the command:
express yourappname
you can then put your html/css/js files inside the express-app -> 'public' folder that you just generated.
After that you create routes inside your app.js by doing something like:
// exampledomain.com/
// Loading the file index.html when user navigates to '/'
app.get('/', function(req, res){
res.sendFile(path.join(__dirname + '/public/index.html'));
});
// or
// exampledomain.com/getFileURL
// POST request (from your ajax) to '/getFileURL'
// which will then load the about.html file into the browser
app.post('/getFileURL', function(req, res){
// Do more JSON/data handling & Node js stuff here then
// send something back
res.sendFile(path.join(__dirname + '/public/about.html'));
});
There're many more useful functions with Express js, but I think Routing is what you need right now.
p.s. Very useful tools to look into when working with Node js:
Postman (Testing ajax/express/Nodejs routes and responses)
Nodemon (Starting Nodejs server automatically on save)

How to receive (and decode) JSON from post data in Node.Js Express?

Suppose I have sent data with the following code:
$.ajax({
type: "POST",
url: "/save/" + #{key},
data: transitions2,
success: function (data) {
},
dataType: "json"
});
where transitions2 is hierarchical JS object.
Now how can I receive it intact at server side
router.post('/save/:key', function(req, res) {
// where is my data here?
});
UPDATE
I found info about body parsers, and found that my site template already contained them. Particularly, app.js contains:
...
var bodyParser = require('body-parser');
...
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/data', express.static(path.join(__dirname, '../data')));
app.use('/', index);
...
So I wrote in my index.js:
...
router.post('/save/:key', function(req, res) {
var transitions = req.body;
image_data.save_transitions(req.params.key, req.query.postfix, transitions);
});
...
Unfortunately, transitions contains
while on client side it contained
i.e. was full of data.
What can be the problem?
UPDATE 2
I tried to do
$.ajax({
type: "POST",
url: "/save/" + #{key},
data: JSON.stringify(transitions2),
success: function (data) {
}
});
and I see in Fiddler2 now, that full Json is passed.
[{"start_image":"20170402_1_NATURAL_COL0R","end_image":"20170409_1_NATURAL_COL0R","transition_classes":["no_transition","some_activity"]},...
Unfortunately, on server side I observe truncated and corrupted string
(equal sign should not be in JSON).
And JSON.parse fails.
use body-parser middleware to retrieve the data.
npm install body-parser
configure this in express app.
Find below the sample code
var bodyParser = require('body-parser');
app.use(bodyParser.json());
Then in your router use the following:
router.post('/save/:key', function(req, res) {
var data = req.body // here is your data
});
The problem was on client side only. Correc way to post complex object with json is:
$.ajax({
type: "POST",
url: "/save/" + #{key},
data: JSON.stringify(transitions2),
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
stringify and contentType are obligatory.
front:
axios.post('/attack', {
number:number,
count:count
},
{
headers:{contentType: "application/json; charset=utf-8"}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}
back:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json())
app.post('/attack', (req, res) => {
let data = req.body
console.log(data)
res.send('200')
})
console log: { number: '(number)', count: '(count)' }

nodeJS - make HTTPS request, sending JSON data

I would like to send an HTTPS POST from one nodeJS server to another. I have some JSON data I would like to send with this request (populated by a html form).
How can I do this? I am aware of https.request() but there does not seem to be an option to include JSON as a part of the query. From my research it seems possible with an HTTP request, but not an HTTPS request. How can I solve this?
const pug = require('pug');
var cloudinary = require('cloudinary');
var express = require('express');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var request = require('request');
var bodyParser = require('body-parser');
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'GET'
};
var app = express();
var parser = bodyParser.raw();
app.use(parser);
app.set('view engine', 'pug');
app.get('/', upload.single('avatar'), function(req, res) {
return res.render('index.pug');
});
app.get('/makeRequest*', function(req, res) {
query = req['query'];
/*
Here, I would like to send the contents of the query variable as JSON to the server specified in options.
*/
});
You can send JSON data through a POST http request with the native https node module, as stated in the documentation
All options from http.request() are valid.
So, taking the http.request() example you can do the following:
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req = https.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
You should edit postData to your desired JSON object
I believe the below is what you want. Using the request library. See comments in the code for my recommendations.
...
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'POST',
json: true
};
...
//making a post request and sending up your query is better then putting it in the query string
app.post('/makeRequest', function(req, res) {
var query = req.body['query'];
//NOTE, you cannot use a GET request to send JSON. You'll need to use a POST request.
//(you may need to make changes on your other servers)
options.body = { payload: query };
request(options, function(err, response, body) {
if (err) {
//Handle error
return;
}
if (response.statusCode == 200) {
console.log('contents received');
}
});
});
as matt mentioned you need to use request
to send JSON object not JSON.Stringify so that at the server you can receive it using:
app.post('/makeRequest', function(req, res) {
console.log (req.body.param1);
}
Use the following code:
var request = require("request");
request({
'url':"http://www.url.com",
method: "POST",
json: true,
body: {'param1':'any value'}
}, function (error, resp, body) {
console.log ("check response.");
});

add new data to server using post method not working. using Reactjs and nodejs

Am not sure which method to use to send data from clientside to server using ajax. am using Post now. below is my code plz review. thanks in adavance
this is my client side code.
$.ajax(
{
url: "/api/addTemplateToDb",
type: 'POST',
data:{
"Name": tempName.value,
"Version": "1.0",
"Data": "{"+ tempData.value +"}"
},
success: function(result) {
console.log(result);
}.bind(this),
error:function(result) {
console.log(result.responseText);
}
}
);
this is my server side(Node) code
app.post('/api/addTemplateToDb', function (req, res) {
console.log(req.body.Name); })
am getting a output as undefined in server.
Insert these two lines(It parses the body) in server side
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

node and express send json formatted

I'm trying to send formatted json with express.
Here is my code:
var app = express();
app.get('/', function (req, res) {
users.find({}).toArray(function(err, results){
// I have try both
res.send(JSON.stringify(results, null, 4));
// OR
res.json(results);
});
});
I get the json in my browser but it's a string.
How can I send it so it's readable in the browser?
try to set the "secret" property json spaces on the Node app.
app.set('json spaces', 2)
This statement above will produce indentation on json content.
You're going to have to set the Content-Type to application/json like this
app.get('/', function (req, res) {
users.find({}).toArray(function(err, results){
res.header("Content-Type",'application/json');
res.send(JSON.stringify(results, null, 4));
});
});
Use type('json') to set Content-Type and JSON.stringify() for formatting:
var app = express();
app.get('/', (req, res) => {
users.find({}).toArray((err, results) => {
res.type('json').send(JSON.stringify(results, null, 2) + '\n');
});
});
Sending JSON output as formatted from the server could be undesirable considering resource usage and performance of the server. Especially in production environments.
Instead, you can find a few ways to format the JSON output at client-side.
If you are using Chrome, you can use an extension among JSON Formatter, JSON Viewer, JSONView or others from Chrome web store.
Firefox provides built-in JSON viewer since Firefox 44.
When using curl or wget in a command line or a shell script, you can pipe the result in JSON into jq.
$ curl http://www.warehouse.com/products | jq .
This should solve your problem
var app = express();
app.set('json spaces', 4)
app.get('/', function (req, res) {
users.find({}).toArray(function(err, results){
res.json(JSON.parse(results));
});
});
For convenience, you can override res.json in a custom middleware that runs before your routes.
To auto-format all JSON responses:
app.use('*', (req, res, next) => {
res.json = (data) => res.type('json').send(JSON.stringify(data, null, 4))
next()
})
app.get('/route', (req, res) => res.json({ formatted: true })
To allow custom formatting based on individual routes or other logic:
app.use('*', (req, res, next) => {
res.json = (...args) => res.type('json').send(JSON.stringify(...args))
next()
})
app.get('/tabs', (req, res) => res.json({ formatted: 'tabs' }, null, '\t')
app.get('/spaces', (req, res) => res.json({ formatted: 'spaces' }, null, 4)
app.get('/minified', (req, res) => res.json({ formatted: false })
Maybe you need to JSON.parse(resp)