POST request through a JSON object - json

I have created a server which serves the post request for a client. I am using the bodyserver, but getting some error
var bodyParser = require('body-parser')
var express = require('express');
var app = express();
app.use(bodyParser.json());
app.post('/v3/botstate/:channel/users/:userid', function (req, res) {
console.log("hsijdaf");
console.log(req.body);
//console.log(req.body);
// res.send('Hello POST');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
A client is as shown below,
var request = require('request');
request.post({
url: "http://localhost:8081/v3/botstate/webchat/users/siddiq",
headers: {
"Content-Type": "application/json"
},
body: '{"jsonrpc":"2.0","id":"zdoLXrB5IkwQzwV2wBoj","method":"barrister-idl","params":[]}',
json:true
}, function(error, response, body){
console.log(error);
console.log(JSON.stringify(response));
console.log(body);
});
while running the client getting the below error,
E:\TESTING>node exp.js
Example app listening at http://:::8081
SyntaxError: Unexpected token "
at parse (E:\TESTING\node_modules\body-parser\lib\types\json.js:83:15)
at E:\TESTING\node_modules\body-parser\lib\read.js:116:18
at invokeCallback (E:\TESTING\node_modules\body-parser\node_modules\raw-body\index.js:262:16)
at done (E:\TESTING\node_modules\body-parser\node_modules\raw-body\index.js:251:7)
at IncomingMessage.onEnd (E:\TESTING\node_modules\body-parser\node_modules\raw-body\index.js:307:7)
at emitNone (events.js:67:13)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:921:12)
at nextTickCallbackWith2Args (node.js:442:9)
at process._tickCallback (node.js:356:17)
please help me in resolving the issue.

You have set Content-Type : application/json in your client, but your POST data is text/plain, not json. That's why body-parser is failing to parse it as it was expecting json through header.
Try after removing ' ' from body in your client.
e.g.
var request = require('request');
request.post({
url: "http://localhost:8081/v3/botstate/webchat/users/siddiq",
headers: {
"Content-Type": "application/json"
},
body: {
"jsonrpc":"2.0",
"id":"zdoLXrB5IkwQzwV2wBoj",
"method":"barrister-idl",
"params":[]
},
json:true
}, function(error, response, body){
console.log(error);
console.log(JSON.stringify(response));
console.log(body);
});
Hope it helps you.

Related

Express routing post call unexpected token in json

I need some help with my routing in Express and making a post call, and retrieving the data within the postrequest.
I've tried retrieving the data by loging req.body but that returns {}, I tried adding the bodyParser to my App.js which gets me the following error when I make a post call:
POST http://localhost:3000/enquete/test/ 400 (Bad Request)
SyntaxError: Unexpected token # in JSON at position 0
This is my code:
App.js
const express = require('express')
const app = express()
var MongoClient = require('mongodb').MongoClient
, co = require('co')
, assert = require('assert')
, bodyParser = require('body-parser');
var indexRouter = require('./routes/index.js');
var enqueteRouter = require('./routes/enquete.js');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'pug');
app.use('/', indexRouter);
app.use('/enquete', enqueteRouter);
app.use(express.static(__dirname + '/routes'));
app.use(express.static(__dirname + '/public'));
app.listen(3000, () => console.log('Example app listening on port 3000!'))
routes/enquete.js
const express = require('express')
var router = express.Router()
router.post('/test/', function(req,res,next){
console.log('request:',req.body);
res.send('hello');
})
module.exports = router;
Ajax post call
function save(array){
$.ajax({
type: 'POST',
data: { name: "Test", location: "TestUSA" },
contentType: 'application/json',
url: 'http://localhost:3000/enquete/test/',
success: function(data) {
console.log('success');
console.log(JSON.stringify(data));
},
error: function(error) {
console.log('error:', error)
}
});
}
Can you use Postman to test the route? Make sure to select x-www-form-urlencoded as the body format since you're using bodyparser.urlencoded({ extended: true })

Nodejs: Post method url body parser shows undefined

I want to use url post params to execute mysql query. I am getting error during mysql command when I post through postman. I dont know what is problem with this code. Here is my code
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var md5 = require('MD5');
var con = mysql.createConnection({
host: "localhost",
user: "shoaib",
password: "",
database: "watch"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.post('/',function(req, res) {
con.connect(function(err) {
var query = "Select * From user Where email=? AND password=?";
var table = [req.body.email,req.body.password ];
console.log(req.body);
query = mysql.format(query, table);
con.query(query, function (err, rows) {
if (err) {
res.json({ "Error": true, "Message": "Error executing MySQL query" });
} else if(rows!=0) {
res.json({ "Error": false, "Message": "Success","Users": rows });
} else {
res.json({ "Error": true,});
}
});
});
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);
Node is working perfectly but when I execute command url I face error.
Make sure on your request that you set the Content-Type header to application/json or application/x-www-form-urlencoded since your app supports either. Without a Content-Type header with either of these values body-parser will not read the request body and res.body will be undefined.
Example POST Request with Content-Type: application/json
const {request} = require('http')
const requestBody = {email: 'abc#gmail.com', password: 'abcdef123456'}
const jsonPostRequest = request({
method: 'POST',
host: 'localhost',
port: 8080,
path: '/api/',
headers: {'Content-Type': 'application/json'}
}, res => {
let chunks = ''
// Handle Response Chunk
res.on('data', chunk => (chunks += chunk))
// Handle Response Ended, print response body
res.on('end', () => console.log(chunks))
})
jsonPostRequest.write(requestBody)
jsonPostRequest.end()

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.");
});

Requesting a JSON using Request module (encoding issue) - Node.js

Im trying to request a Json file from a server different from mine but i cant set the right encoding.
I tried using HTTP module and failed.
Now im trying to do this using the 'Request' module.
The response i get is encoded to i dont know what. maybe utf 16 and is not readable at all.
Note: The json has some Hebrew chars in it.
I added the following to try and fix it but also failed:
headers: {'Content-Type': 'application/json; charset=utf-8'}
My code:
var http = require('http');
var request = require('request');
var express = require('express');
var app = express();
var url = 'http://www.oref.org.il/WarningMessages/alerts.json?v=1';
app.listen(process.env.PORT || 8080);
app.get('/', function(req,res){
res.send("Red color");
});
// get Alerts from web-service
app.get('/getAlerts', function(req,res){
request({
url: url,
json: true,
headers: {'Content-Type': 'application/json; charset=utf-8'}
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(response.headers) // Print the json response
res.set({
'content-type': 'application/json'
}).send(body);
}
})
});
That API returns a JSON response encoded in UTF-16-LE, so you'll have to tell request to use that encoding instead.
However, since you're trying to query Pikud Haoref's alerts API, check out pikud-haoref-api on npm to do the heavy lifting for you:
https://www.npmjs.com/package/pikud-haoref-api

Error in parsing JSON in Nodejs from Posted data

I have used this jquery ajax code to pass JSON:
var jsonObjects = [{id:1, name:"amit"}];
$.ajax({
type: 'GET',
url: 'http://localhost:8080',
data: {
jsonData: JSON.stringify(jsonObjects)
},
dataType: 'json',
complete: function(validationResponse) {
}
});
I have used this node js code to parse JSON data:
http.createServer(function (request, response) {
response.writeHeader(200, {
"Content-Type": "text/plain"
});
response.writeHead(200, {"Content-Type":"text/plain"});
var theUrl = url.parse(request.url);
var queryObj = queryString.parse( theUrl.query );
var obj = JSON.parse( queryObj.jsonData);
console.log(obj[0].id)
response.write(String(obj[0].id))
response.end();
}).listen(8080,'127.0.0.1');
but it displays following error in console:
undefined:1
rn┴P║Eee
^
SyntaxError: Unexpected token u
at Object.parse (native)
at Server.<anonymous> (C:\node\nodejs\node_modules\17-8-12\tracker.js:79:22)
at Server.emit (events.js:70:17)
at HTTPParser.onIncoming (http.js:1610:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:91:29)
at Socket.ondata (http.js:1506:22)
at TCP.onread (net.js:374:27)
Then the code stops..
This section:
response.writeHeader(200, {
"Content-Type": "text/plain"
});
response.writeHead(200, {"Content-Type":"text/plain"});
Seems garbled: is that your real code? If so, remove the first three lines. If that doesn't fix it, console.log request.url first, then queryObj.jsonData and see if they're reasonable.
This isn't a direct answer for your issue but I would suggest checking out Express and the bodyParser middleware.
They you can do something like:
var express = require('express');
var app = express();
app.get('/', function(req, res){
console.log(req.query.jsonData);
res.send('return data here');
});
app.listen(8080);