Allowing Another Origin
Part of the REST APIs section of Coddy's Node.js journey. Lesson 19 of 25.
A page on one origin needs permission to read an API response from another. The browser sends an Origin request header. The API can answer with Access-Control-Allow-Origin naming the permitted origin.
if (req.get('origin') === 'https://shop.example.com') {
res.set('Access-Control-Allow-Origin', 'https://shop.example.com');
}The browser checks this response header before exposing the response to the page. The API may still receive the request: CORS is not a login check. The request bar does not enforce CORS, but its Headers tab lets you inspect what a browser would receive.
req.get('origin') reads the request’s Origin header. Header names ignore case.
Challenge
EasyThis is a small practice project. Its setup is provided; edit only server.js.
In the supplied GET route, set Allow-Origin only when Origin equals https://board.example.com. Keep the JSON response. Run, then send GET /result with that Origin header: the response header must match. A different or missing Origin gets no Allow-Origin header.
In the request bar’s Headers field, enter Origin: https://board.example.com. Inspect the response headers to see the permission.
Try it yourself
import express from 'express';
const app = express();
app.get('/result', (req, res) => {
res.json({ ok: true });
});
app.listen(3000);
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST4Browsers, Versions and Config
What Is an OriginAllowing Another OriginCORSA Page That Calls the APIPractice on your own: Express playground