Express JS Express Request and Response 2 — Questions and Answers
Question 1: What does res.sendFile() do in Express?
- Sends a file as the HTTP response with appropriate Content-Type (Correct answer)
- Uploads a file to the server
- Streams a file to another server
- Caches a file in memory
Correct answer: Sends a file as the HTTP response with appropriate Content-Type
res.sendFile() transfers a file at the given path as the response, automatically setting the Content-Type header.
Question 2: Which method chains status code setting and sends a response in a single line?
- res.status(200).json(data) (Correct answer)
- res.code(200).send(data)
- res.setCode(200).write(data)
- res.respond(200, data)
Correct answer: res.status(200).json(data)
res.status() returns the response object, allowing you to chain .json() or .send() on the same line.
Question 3: How do you set a response header in Express?
- res.set('Header-Name', 'value') or res.setHeader() (Correct answer)
- res.header['Header-Name'] = 'value'
- res.addHeader('Header-Name', 'value')
- res.headers.push()
Correct answer: res.set('Header-Name', 'value') or res.setHeader()
res.set() (or res.header()) sets response headers, supporting both single and multiple header values.
Question 4: What does req.ip contain in an Express application?
- The IP address of the remote client (Correct answer)
- The server's IP address
- The IP of the last proxy
- An array of all IP addresses
Correct answer: The IP address of the remote client
req.ip contains the remote IP address of the request, or the leftmost IP from X-Forwarded-For if trust proxy is enabled.
Question 5: Which property contains the full URL path including the query string in Express?
- req.originalUrl (Correct answer)
- req.path
- req.url
- req.fullPath
Correct answer: req.originalUrl
req.originalUrl preserves the original request URL including the full path and query string, even within mounted routers.
Question 6: How do you force a file download response (with Content-Disposition attachment) in Express?
- res.download(filePath) (Correct answer)
- res.sendFile(filePath, { attachment: true })
- res.attach(filePath)
- res.file(filePath, 'download')
Correct answer: res.download(filePath)
res.download() transfers a file and sets Content-Disposition to 'attachment', prompting the browser to download it.
What does res.sendFile() do in Express?