On this page
A link to a content endpoint may open HTML in a browser while a JavaScript request to the same endpoint receives JSON. Before attributing that difference to browser compatibility, compare the actual requests and responses: redirects, format parameters, Accept, and Content-Type can all matter.
This experiment uses a local server and DevTools to compare ordinary navigation with explicit fetch() requests. It is intended for your own machine or another environment you are authorized to test.
Key Takeaways
- An ordinary
<a>link does not give its author a general way to set arbitrary request headers, includingAccept. - A script can supply
Accepttofetch(), but that is a different request from a navigation and may be subject to CORS. - Inspect every redirect hop and the final response's
Content-Type. A different URL alone does not prove that theAcceptheader changed. - Record browser names, versions, operating system, URLs, headers, and results when performing a compatibility review.
What the experiment compares
The local server below exposes one endpoint through a redirect. It chooses HTML or JSON using a deliberately simplified rule: a format query parameter wins; otherwise, an Accept value containing application/json selects JSON. This is not a complete implementation of HTTP content negotiation: it does not parse media ranges, preferences, or quality values.
The test page provides links to the same endpoint with and without format parameters. It also provides buttons that fetch the endpoint with explicit Accept headers. Comparing the automatic link with the same-origin JSON fetch is especially useful: both begin at the same URL, but they are different kinds of request.
No browser was used to prepare this article, and the code was not executed here. Current browser documentation and RFC 9110 were not available to consult in this run; verify behavior and compatibility in the browsers and environments you intend to support.
Advertisement
Run a local comparison
You need Node.js and a browser with developer tools. Save the following as accept-lab.js. It uses Node's built-in HTTP server and starts two loopback-only servers, on ports 8000 and 8001. If either port is occupied, stop the conflicting process or change the ports consistently in the code.
const http = require('node:http');
const page = `<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Accept header lab</title></head>
<body>
<h1>Accept header lab</h1>
<p>Open DevTools and enable Preserve log in the Network panel.</p>
<ul>
<li><a href="/start">Navigate: automatic format</a></li>
<li><a href="/start?format=html">Navigate: HTML parameter</a></li>
<li><a href="/start?format=json">Navigate: JSON parameter</a></li>
</ul>
<button id="html">Fetch HTML, same origin</button>
<button id="json">Fetch JSON, same origin</button>
<button id="blocked">Fetch JSON, other origin, no CORS</button>
<button id="allowed">Fetch JSON, other origin, with CORS</button>
<pre id="result"></pre>
<script>
async function run(url, accept) {
const result = document.getElementById('result');
result.textContent = 'Requesting...';
try {
const response = await fetch(url, { headers: { Accept: accept } });
const body = await response.text();
result.textContent = 'Final URL: ' + response.url +
'\\nStatus: ' + response.status +
'\\nContent-Type: ' + response.headers.get('content-type') +
'\\nBody: ' + body;
} catch (error) {
result.textContent = 'Fetch failed: ' + error.message;
}
}
document.getElementById('html').onclick = () => run('/start', 'text/html');
document.getElementById('json').onclick = () => run('/start', 'application/json');
document.getElementById('blocked').onclick = () =>
run('http://127.0.0.1:8001/start', 'application/json');
document.getElementById('allowed').onclick = () =>
run('http://127.0.0.1:8001/start?cors=1', 'application/json');
</script>
</body>
</html>`;
function handle(req, res) {
const url = new URL(req.url, 'http://127.0.0.1');
console.log(JSON.stringify({
host: req.headers.host,
method: req.method,
path: url.pathname + url.search,
accept: req.headers.accept ?? null
}));
// Lab-only CORS policy. Do not copy this unrestricted policy to production.
if (url.searchParams.get('cors') === '1') {
res.setHeader('Access-Control-Allow-Origin', '*');
}
res.setHeader('Cache-Control', 'no-store');
if (req.method !== 'GET') {
res.writeHead(405, { Allow: 'GET' });
res.end();
return;
}
if (url.pathname === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(page);
return;
}
if (url.pathname === '/start') {
res.writeHead(302, { Location: '/resource' + url.search });
res.end();
return;
}
if (url.pathname !== '/resource') {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not found');
return;
}
const format = url.searchParams.get('format');
if (format !== null && format !== 'html' && format !== 'json') {
res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Unsupported format');
return;
}
const wantsJson = format === 'json' ||
(format === null && (req.headers.accept || '').includes('application/json'));
res.setHeader('Vary', 'Accept');
if (wantsJson) {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ message: 'Hello from the lab' }));
} else {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end('<!doctype html><html><body><p>Hello from the lab</p></body></html>');
}
}
for (const port of [8000, 8001]) {
const server = http.createServer(handle);
server.on('error', (error) => {
console.error('Server error on port ' + port + ': ' + error.message);
process.exitCode = 1;
process.exit();
});
server.listen(port, '127.0.0.1', () => {
console.log('Listening on 127.0.0.1:' + port);
});
}
Start it from the directory containing the file:
node accept-lab.js
Open http://127.0.0.1:8000/. Keep the terminal visible for request logs. Stop the servers with Ctrl+C when finished.
Inspect the navigation and fetch requests
- Open the browser's Network panel. Enable Preserve log so the initial request and redirect remain visible after navigation.
- Follow Navigate: automatic format. Inspect the request to
/startand the redirected request to/resource. Record each request'sAccept, the redirect'sLocation, and the final response's status andContent-Type. Return to the test page. - Click Fetch JSON, same origin. Inspect the same fields for both hops and compare them with the navigation. The server is designed to select JSON for this explicit header.
- Compare the HTML and JSON parameter links. Both parameters are carried through the redirect; the lab's parameter rule selects the representation. Do not infer that their
Acceptheaders differ without inspecting them. - Compare the two other-origin fetch buttons. Port 8001 is a different origin from port 8000. The no-CORS response is intended to make the browser reject script access; the
cors=1variant adds an allowing header to both the redirect and final response. Check the Network panel and console if the first fetch fails.
The terminal logs the Accept value received by the server at each hop. DevTools shows the browser's view; comparing both helps identify where a redirect or other intermediary changed the request. A failed cross-origin fetch does not necessarily mean the server received no request.
Advertisement
Interpret the results
Redirects
The initial /start response is a redirect, not the final representation. Inspect its Location and then inspect the request and response for /resource. Real deployments may redirect to another host or origin, so a comparison that only captures the first URL can miss the request that selected the final format.
Accept and Content-Type
Accept describes response media types a client is prepared to receive; Content-Type describes the representation actually returned. In this lab, the server uses its simplified rule to choose a response. A real server may use different negotiation rules, ignore Accept, honor an explicit format parameter, or return an error when it cannot provide an acceptable representation.
The browser decides how to handle a navigated response based on the response and browser behavior. Do not assume every browser will display a JSON navigation identically. Conversely, fetch() returns a response to script rather than navigating the page; using response.text() in the lab lets you inspect either body as text.
CORS
CORS controls whether browser JavaScript can access a cross-origin response. It is not the same as ordinary navigation. A cross-origin navigation may succeed while a cross-origin fetch fails. Redirects complicate the comparison: CORS requirements can apply during the redirect chain as well as to the final response.
The lab's wildcard CORS header is for an isolated demonstration without credentials. Production endpoints should choose an appropriate origin and credential policy instead of copying it blindly. If you change methods or headers, the browser may also make a preflight request; inspect that request and its response separately.
Common Mistakes
- Changing the URL and declaring an
Acceptdifference. Query parameters may independently select a representation. Capture the actual request headers. - Comparing only final URLs. Record the redirect status,
Location, request headers at each hop, and finalContent-Type. - Treating a CORS error as a negotiation error. A server can return a valid representation that browser JavaScript is not allowed to read.
- Assuming the lab implements full negotiation. Its substring check deliberately ignores preference weights and other media-range details.
- Testing only a cached response. The lab sends
Cache-Control: no-store; when examining another endpoint, account for caches and whether representations vary byAccept.
Best Practices for a Browser Review
Use a small results table for each browser and version: starting URL, request type, redirect chain, observed Accept, final status, Content-Type, and whether the body was accessible or displayed. Repeat with the same test data and server configuration. Include operating system and any relevant proxy or extension in your notes.
For production endpoints, define when a URL parameter overrides negotiation and configure caches for the representations actually served. If responses vary by Accept, ensure the caching configuration accounts for that header; Vary: Accept is one part of communicating that distinction.
Conclusion
Compare a navigation and an explicit fetch against the same starting URL, then inspect every hop. The resulting evidence separates URL-based format selection, header-based negotiation, redirects, and CORS from genuine browser-specific behavior.
What would your domain sell for?
A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.