Menu
CoddyTech

What Is an Origin

Part of the REST APIs section of Coddy's Node.js journey. Lesson 18 of 25.

A browser normally lets a page’s JavaScript read API responses from its own origin. This same-origin rule prevents a page from freely reading another site’s data. CORS, Cross-Origin Resource Sharing, lets a server permit another origin with response headers.

A browser page has an origin: its scheme, host and port together. Different paths on the same origin can share an API without CORS permission. A changed host, scheme or port makes a different origin.

new URL('https://board.example.com/tasks').origin;
// 'https://board.example.com'
new URL('https://board.example.com/help').origin;
// the same origin

URL is a built-in class that reads an address into named parts. Its origin property excludes the path and query. The supplied page address is fixed in the starter. This practice compares origins; the next step will let a server grant permission across them.

A request’s Origin header already contains this origin value; the next lesson reads that header.

challenge icon

Challenge

Easy

This is a small practice project. Its setup is provided; edit only exercise.js.

Return {"same":true} when the supplied address shares the page origin, otherwise false. POST {"address":"https://board.example.com/api/tasks"} to /result gives true. Changing https to http, the host, or the port gives false. Addresses in this exercise are valid absolute URLs.

The initial GET /result uses the supplied example {"address": "https://board.example.com/api/tasks"}. Use POST /result with a JSON body to try other inputs.

Try it yourself

const page = 'https://board.example.com/tasks';
export function exercise({ address }) {
    return { same: address === page };
}

All lessons in REST APIs

Practice on your own: Express playground