My index.js file looks like this
var http = require('http');
var url = require('url');
var server = http.createServer(function (req, res) {
var parseUrl = url.parse(req.url, true);
var path = parseUrl.pathname;
var parsedurl = url.parse(req.url, true);
// Get the path
var path = parsedurl.pathname;
var trimmedPath = path.replace(/^\/\/ $/, '');
var queryStringObject = parsedurl.query;
// Get the HTTP Method
var method = req.method.toLowerCase();
// Send the response
res.end('Hello World\n');
// Log the request path
console.log(
'Request received on path:'
trimmedPath
'with method'
method
'query'
queryStringObject
);
});
server.listen(5000, function () {
console.log(`Server is listening kamal`);
});
My terminal Error screenshot I don't know why I am facing this error, to the best of my knowledge the code looks correct ?
CodePudding user response:
You can't concatenate objects to strings. You could explicitly convert the queryStringObject to a string (e.g., by using JSON.stringify), but since you aren't using the parsed querystring and just want to display, you could just avoid parsing the querystring when you parse the URL:
var parseUrl = url.parse(req.url);
// Second arg (true) removed ---^
CodePudding user response:
Your error states that you are trying to use an object as a primitive value string, number, boolean.
url.parse(req.url,true).query returns an object, eg:{ foo: 'bad', baz: 'foo' }. You cannot simply add it to a string without prior conversion.
Try using JSON.stringify() :
console.log('Request received on path:' trimmedPath 'with method' method 'query' JSON.stringify(queryStringObject));
or maybe takeout individual query params and add to the string (based on your use case).
