Json result with "undefined" prefixed - node.js

I use node https module to get auth information from another server, I get the result is "result=undefined{a:...,b:...}", so I can't use JSON.parse to parse the result data, but if I use "JSON.parse(body.substr(9))", I can get the right result.
For more information, if I use a post tool to fetch the result, I get the result type is "application/json" and the result is the right json object. I use the following code to fetch post result.
var options={
hostname:...,
port:null,
path:...,
method:'post',
rejectUnauthorized:false,
requestCert:true,
agent:false
}
var https.request(options,function(res){
var body;
res.on('data',function(chunk){
body+=chunk;
});
res.on('end',function(){
console.log(JSON.parse(body));
});
});

You should initialize body with an empty string:
var body = '';
because otherwise, the first time
body+=chunk;
is called, body is undefined and gets concatenated as the "undefined" string:
> var body;
undefined
> body += "{}"
'undefined{}'
> var body = '';
undefined
> body += "{}"
'{}'

Related

SyntaxError: Unexpected number in JSON at position 1 in Node

In Nodejs, I am trying to parse json data in node http.createServer post request. I am following this tutorial and written followig code.
var data;
req.on('data', function(chunk) {
data = JSON.parse(chunk.toString()); // parsing request body json object
});
req.on('end', function() {
console.log(data);
});
Where I am parsing data, it is giving me syntax error SyntaxError: Unexpected number in JSON at position 1
I have also tried converting this line into following.
var data, value = {};
req.on('data', chunk => {
value = chunk.toString(); // parsing request body json object
data = JSON.parse(value);
});

TypeError: Request path contains unescaped characters, any idea

//route to search (POST http://localhost:8080/api/search)
apiRoutes.post('/search', function(req, res) {
console.log('search');
var query = req.params;
console.log(query);
options = {
protocol : "https:/",
host: "https://api.themoviedb.org",
path: "/3/search/movie?api_key=35f7a26be584f96e6b93e68dc3b2eabd&language=en-US&page=1&include_adult=false&query="+query,
};
var req = https.request(options, function(res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write("{}");
req.end();
})
DOES ANYONE KNOW WHERE THE PROBLEM IS?
I'm trying to do a request to do a research to the api the movie db and get the result back
There are some problems with the code. I have tested it and made it to work.
let options = {
host: "api.themoviedb.org",
path: "/3/search/movie?api_key=35f7a26be584f96e6b93e68dc3b2eabd&language=en-US&page=1&include_adult=false&query="+query.data.replace(' ','%20'),
};
first of all since you are using https module you don't need to specify the protocol nor you need to put it in the url. That's how your options variable should be.
Second you are appending the entire query object to the url which is {} instead you should append a string which will be in one of the key of your query object in my case its query.data
Third if there are spaces in the string Eg: Home Alone you to maintain space and avoid the error we replace the string with %20 which is a escaping character.
Forth Try giving a unique name for https request variable and its response variable in the callback function or it will override the route's req res variables cause your code to not work. Notice how I have used route's res function to send the data back and end the response
Also I am getting the data in req.body and you are using req.params however there are no params defined in your routes. Try going through the documentation for more information
Here is the complete code
apiRoutes.post('/search',function (req, res) {
https = require('https');
var query = req.body;
console.log(query.data);
let options = {
host: "api.themoviedb.org",
path: "/3/search/movie?api_key=35f7a26be584f96e6b93e68dc3b2eabd&language=en-US&page=1&include_adult=false&query="+query.data.replace(' ','%20'),
};
var request = https.request(options, function(response) {
var chunks = [];
response.on("data", function (chunk) {
chunks.push(chunk);
});
response.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
res.send(body);
res.end()
});
});
request.end();
});
Hope it helps.

Get the response "ContentType" in a nodejs http request

I want to donwload a file via http and check the "ContentType" response header. My Download looks like this:
var fileUrl = "<url>";
var request = https.get(fileUrl, function (res) {
res.on('data', function (data) {
//...
});
res.on('error', function (error) {
//...;
});
I get the data, but is there any way to acces the content type resonse header?
The res variable is an instance of http.IncomingMessage, which has a headers property that contains the headers:
var request = https.get(fileUrl, function (res) {
var contentType = res.headers['content-type'];
...
});
If you want to get only mime-type, be aware that Content-Type header can include other information such as charset or boundary.
Use parser such as content-type-parser instead of reading header directly.
const contentTypeParser = require("content-type-parser");
const contentType = contentTypeParser(req.headers['content-type']);
const mimeType = contentType.type+'/'+contentType.subtype;

Getting request body from response object

I'm trying to retrieve the body of a request via the response object.
var request = require('request');
request({
...
body: {
foo: 'bar'
}
}, function(err, res, body) {
var reqBody = res.request.body;
});
But the request body is now a Buffer. How can I turn this back into a JavaScript object?
Note: I can't store the request body in a variable with larger scope before making the http request.
Figured it out, way simpler than I thought.
var reqBody = res.request.body.toString();
reqBody = JSON.parse(reqBody);
First convert it to JSON, then convert the JSON to a JavaScript object.

Simple Node.js server no data received from post.

I have set up a simple server in Node.js. I am trying to get the post data from the request. I have tried sending the data with $.post() and by a simple HTML form with method="post"
if(request.method.toUpperCase() === "POST") {
var $data;
request.on("data", function (chunk) {$data += chunk});
request.on("end", function ()
console.log($data);
});
var message = "Settings Saved"
response.writeHead(
"200",
"OK",
{
"access-control-allow-origin" : origin,
"content-type" : "text/plain",
"content-length" : message.length
}
);
return(response.end(message));
}
Node returns the Status:200 and everything looks good, but no matter where I put it, the console.log($data) always spits out undefined (BTW I have also tried this without the $ under a different variable name).
Looking at all the other SO questions about this that I could find did not have a solution for me.
use var $data = '';
not var $data;
var $data; // $data === undefined.
//...
$data += chunk // undefined + 'string' === 'undefined'

Resources