Express JS Express Request and Response 1 — Questions and Answers
Question 1: Which property of the request object contains the parsed body of a POST request with JSON content?
- req.body (Correct answer)
- req.data
- req.payload
- req.content
Correct answer: req.body
After applying express.json() middleware, the parsed JSON body is available on req.body.
Question 2: How do you send a JSON response in Express?
- res.json(data) (Correct answer)
- res.send(JSON.stringify(data))
- res.write(data)
- res.json = data
Correct answer: res.json(data)
res.json() automatically sets Content-Type to application/json and serializes the given object.
Question 3: Which method sets the HTTP status code of a response in Express?
- res.status(code) (Correct answer)
- res.code(code)
- res.httpStatus(code)
- res.setStatus(code)
Correct answer: res.status(code)
res.status() sets the HTTP status code for the response and returns the response object for chaining.
Question 4: How do you retrieve the value of the 'Authorization' request header in Express?
- req.get('Authorization') or req.headers['authorization'] (Correct answer)
- req.header.Authorization
- req.headers.Authorization
- req.getHeader('Authorization')
Correct answer: req.get('Authorization') or req.headers['authorization']
req.get() retrieves a request header case-insensitively, or you can access req.headers directly using lowercase keys.
Question 5: What is the difference between res.send() and res.end() in Express?
- res.send() sets headers and body; res.end() is lower-level and sends no body by default (Correct answer)
- They are identical
- res.end() sets JSON content type
- res.send() is deprecated
Correct answer: res.send() sets headers and body; res.end() is lower-level and sends no body by default
res.send() sets Content-Type and Content-Length automatically; res.end() is a raw Node.js method with no automatic header handling.
Question 6: How do you redirect a client to a different URL in Express?
- res.redirect(url) (Correct answer)
- res.location(url)
- res.goto(url)
- res.forward(url)
Correct answer: res.redirect(url)
res.redirect() sends an HTTP redirect response with a 302 status by default, or a specified status code.
Which property of the request object contains the parsed body of a POST request with JSON content?