Creating an API
Learn how to create an API to extend web server functionalities and services.
We'll cover the following
Your web server is pretty limited for now, handling only one route and always returning the same string. Let’s create your own little API by publishing some data in JSON format.
Enabling AJAX requests
Authorizing cross-origin requests on your server is mandatory to accept AJAX calls from clients. Enabling CORS on an Express web server is done by the following code:
// Enable CORS (see https://enable-cors.org/server_expressjs.html)
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
Get hands-on with 1400+ tech skills courses.