Tell us what’s happening:
I am getting unexpected result from the code below.
What am I missing please?
// Get Query Parameter Input from the Client
app.get(“/name”, function(req, res) {
var { first: firstName, last: lastName } = req.query;
console.log(${firstName} ${lastName}
);
});
I am getting the following result:
Restarting ‘server.js’
Node is listening on port 3000…
Mick Jagger/name?first=Mick,Jagger
Mick,Keith Jagger/name?last=Richards
###Your project link(s)
solution: http://localhost:3000/name?first=Mick&last=Jagger
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0
Challenge Information:
Basic Node and Express - Get Query Parameter Input from the Client
Try console logging req.query
to see what it returns
When I try console.log(req.query); I got the following results:
Node is listening on port 3000…
{ first: ‘Mick’, last: [ ‘Jagger/name?first=Mick’, ‘Jagger’ ] }
{ first: [ ‘Mick’, ‘Keith’ ], last: ‘Jagger/name?last=Richards’ }
Kind of odd in my opinion…
Are you getting an error message?
No, I am not getting an error message.
To resolve the issue, I had to hack the result with the following if … else check cases in order to move forward.
if (firstName === 'Mick'){
fullName = 'Mick Jagger';
} else if (firstName === 'Keith'){
fullName = 'Keith Richards';
} else if (Array.isArray(firstName) && firstName.length > 1 && firstName[1] === 'Keith'){
fullName = 'Keith Richards';
} else {
fullName = `${firstName} ${lastName}`;
}
Thank you for assisting.
Your solution should work for any name. Hardcoding values like this is incorrect.
I completely agree with you that it is not a solution. It is rather a hack as stated.
The button action to complete the challenge appears to be returning unexpected data, this hard hack should not be used as a solution.
Do you know where I can find the source code for the “I’ve completed this challenge” button for further inspection?
I see…
If you query it with any other name what does the console.log look like?
Are you logging req.query before splitting it into the variable? Print it as the first step of your function and share the code please.
This is the problem:
You aren’t parsing req.query
correctly. If you log req.query
as originally suggested, it might help to parse it. It’s an object and you should parse it like an object:
https://www.geeksforgeeks.org/express-js-req-query-property/
In the initial code, you are not responding, only logging. Also, as said, that isn’t the response format asked for.
Respond with a JSON document, taking the structure { name: 'firstname lastname'}
.
app.route("/someRoute").get((req, res) => {
const { firstProp, nextProp } = req.query;
res.json({ someProp: `${firstProp} ${nextProp}` });
});
The tests, not that it should matter.
https://github.com/freeCodeCamp/freeCodeCamp/blob/main/curriculum/challenges/english/05-back-end-development-and-apis/basic-node-and-express/get-query-parameter-input-from-the-client.md
I am still getting unexpected result using other name(s).
Code:
// Get Query Parameter Input from the Client
app.get("/name", function(req, res) {
console.log(req.query);
console.log(`${req.query.first} ${req.query.last}`);
// res.json({
// name: `${req.query.first} ${req.query.last}`
// });
});
Result: when using Hello World
Hello World/name?first=Mick,Jagger
Hello,Keith World/name?last=Richards
Result: when using John Doe
John Doe/name?first=Mick,Jagger
John,Keith Doe/name?last=Richards
Result: when logging req.query
{ first: ‘John’, last: [ ‘Doe/name?first=Mick’, ‘Jagger’ ] }
John Doe/name?first=Mick,Jagger
{ first: [ ‘John’, ‘Keith’ ], last: ‘Doe/name?last=Richards’ }
John,Keith Doe/name?last=Richards
I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>
) to add backticks around text.
See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').
Why is your response commented out in the code you posted?
1 Like
I still get the same unexpected data when I uncomment the response call.
res.json({
name: `${req.query.first} ${req.query.last}`
});
I don’t know what you mean by unexpected data?
As for the format, look at the Nodejs docs to see why/when an array is used.
https://nodejs.org/api/querystring.html#querystringparsestr-sep-eq-options
For example, the query string 'foo=bar&abc=xyz&abc=123'
is parsed into:
{
"foo": "bar",
"abc": ["xyz", "123"]
}
Querystring in URL: ?first=John&last=Doe
console.log(req.query);
console.log(`${req.query.first} ${req.query.last}`);
Result Print:
{ first: ‘John’, last: [ ‘Doe/name?first=Mick’, ‘Jagger’ ] }
John Doe/name?first=Mick,Jagger
Should be:
{ first: ‘John’, last: ‘Doe’ }
John Doe
Is the code you posted passing or not?
I don’t know what it is you are asking about anymore.
With the code you posted
app.get("/name", function(req, res) {
console.log(req.query);
console.log(`${req.query.first} ${req.query.last}`);
res.json({
name: `${req.query.first} ${req.query.last}`
});
});
First test logs
{ first: 'Mick', last: 'Jagger' }
Mick Jagger
Last tests logs:
{ last: 'Richards', first: 'Keith' }
Keith Richards
The tests are sending its own query strings.
The code is not passing.
So, I am logging the request data to analyze it.
Base on this querystring - ?first=John&last=Doe , the console output appears to be wrong.
First Test logs:
{ first: 'John', last: [ 'Doe/name?first=Mick', 'Jagger' ] }
John Doe/name?first=Mick,Jagger
Second Test logs:
{ first: [ 'John', 'Keith' ], last: 'Doe/name?last=Richards' }
John,Keith Doe/name?last=Richards
Could it be because I am using my local environment for testing?
However, all other courses challenge pass until this point.
Do you have other routes that would handle the same request you maybe didn’t remove?
Because the only test that is using John Doe is the body parser challenge, and it is on a POST request, not a GET.
You should not be getting John Doe as part of the GET for /name
I have every other test commented out.
I started noticing the problem while using Mick Jagger in the querystring. So, I decided to use John Doe to further troubleshoot the issue.
The concern that I am having is that if I am passing a first and last name querystring, why am I getting such output from req.query object?
Can you please share your full code as it is now?
rofamax
August 28, 2024, 11:38pm
20
require('dotenv').config()
let express = require('express');
let app = express();
let bodyParser = require("body-parser");
const path = require('path');
app.get("/name", function(req, res) {
console.log(req.query);
console.log(`${req.query.first} ${req.query.last}`);
res.json({
name: `${req.query.first} ${req.query.last}`
});
});
module.exports = app;