Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set headers to all responses in Koa.js?

In Express.js I used to have this kind of code:

app.use((req, res, next) => {   res.header('Access-Control-Allow-Origin', '*');   res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');   res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');   next(); }); 

How do I do the same thing with Koa.js? I need to preset these several http headers for each server response.

like image 840
Gherman Avatar asked Apr 03 '18 14:04

Gherman


People also ask

How do I add a header in node JS?

setHeader(name, value) (Added in v0. 4.0) method is an inbuilt application programming interface of the 'http' module which sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced.

What does Response setHeader do?

setHeader. Sets a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.

What is Koa NPM?

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling.


1 Answers

Finaly I found how to do it.

app.use(async (ctx, next) => {   ctx.set('Access-Control-Allow-Origin', '*');   ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');   ctx.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');   await next(); }); 
like image 63
Gherman Avatar answered Oct 07 '22 06:10

Gherman