In this lesson, you will learn how to implement content negotiation to ensure your server sends data in the exact format your client expects.
Understanding Media Negotiation
When a client makes an HTTP request, it doesn't always want plain HTML. It might prefer JSON for a mobile app or XML for a legacy system. The "MIME Type" (Multipurpose Internet Mail Extensions) acts as a label—like application/json or text/html—that tells the recipient exactly what kind of data they are receiving.
Content negotiation is the process where the client tells the server what it prefers, and the server decides what to provide. This communication happens through the Accept header.
Implementing the Logic
In a Node.js server, you can inspect the Accept header to decide how to format your response. Here is a simple way to implement this logic:
const http = require('http');
const server = http.createServer((req, res) => {
const acceptHeader = req.headers['accept'];
const data = { message: "Hello, World!" };
// Check if the client prefers JSON
if (acceptHeader === 'application/json') {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(data));
}
// Default to plain text
else {
res.setHeader('Content-Type', 'text/plain');
res.end(data.message);
}
});
server.listen(3000);
Why It Matters
By checking the Accept header, your API becomes flexible. Instead of creating separate endpoints for every data format, you create one intelligent route that respects the client's needs. If the client asks for application/json, you serialize your objects accordingly; if they don't specify or ask for something else, you fall back to a safe default like text/plain.
Remember that the Content-Type header you send back must match the actual structure of the body you write. If you send a JSON string but label it as text/html, the browser or client application may attempt to parse it incorrectly, leading to crashes or garbled data.
Key Takeaway: Content negotiation uses the Accept request header to determine the appropriate response format, which must be clearly declared to the client using the Content-Type response header.