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);
Related
I am supposed to send data from an app to the server and the post method from that app is made using content type as application/json but it is plain text. I cannot update the app to change this header now. The current app is working as the data reaches PHP directly and PHP doesn't parse the incoming data which is specified as json.
import express from 'express'
var http = require('http')
const redirectionRoutes = express.Router()
redirectionRoutes.use(function(req, res, next) {
req.rawBody = ''
req.headers['content-type'] = 'text/plain'
req.on('data', function(chunk) {
req.rawBody += chunk
})
req.on('end', function() {
next()
})
})
redirectionRoutes.post(/^\/update_services\/.*$/, function(request, response) {
var data = request.rawBody
var dataLength = data.length
var options = {
hostname: 'localhost',
port: 80,
path: request.path,
method: 'POST',
json: false,
headers: {
'Content-Type': 'text/plain',
'Content-Length': dataLength
}
}
var buffer = ''
var req = http.request(options, function(res) {
res.on('data', function(chunk) {
buffer += chunk
})
res.on('end', function() {
response.send(buffer)
})
})
req.write(data)
req.end()
})
But in nodejs(my application), as the content type is specified as json, the body parser is parsing the data and as it's not json, I am getting an error:
SyntaxError: Unexpected token # in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (../node_modules/body-parser/lib/types/json.js:157:10)
at parse (../node_modules/body-parser/lib/types/json.js:83:15)
at /Users/../node_modules/body-parser/lib/read.js:116:18
at invokeCallback (/Users/../node_modules/body-parser/node_modules/raw-body/index.js:224:16)
at done (/Users/../node_modules/body-parser/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/Users/../node_modules/body-parser/node_modules/raw-body/index.js:273:7)
at emitNone (events.js:105:13)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1047:12)
Is there a way in nodejs/body parser to not to parse this incoming json and let is get into the function as plain text.
It is solved!!
I am exporting this module at the end of the app code along with other pages routers. So, the body-parser being called in previous libraries are being called if I didn't use in this particular router.
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)' }
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.");
});
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.
We are attempting to extract a JSON Object from a URL through http requesting. However, when we consistently getting the "undefined" when we try to return the text. Is there a problem in the way that we are implementing the http request?
function getUserData(email) {
var pathURL = "/" + email + "/data"
var options = {
host: 'localhost',
port: 3000,
path: pathURL,
method: 'GET',
headers: {
accept: 'application/json'
}
};
var x = http.request(options, function(res){
console.log("Connected");
res.on('data', function(data){
console.log(data);
});
});
}
Close the http.request() by using
x.end();
Here a reference to a similar question.
Sending http request in node.js
Try logging error as:
req.on('error', function(err){
console.log('problem with request:',err.message);
});
Meanwhile check the documentation of http library as well.
The response body are data but not returning to x.
var body = []
request.on('data', function(chunk) {
body.push(chunk)
}).on('end', function() {
body = Buffer.concat(body).toString()
// all is done, you can now use body here
})