Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Express JS .all() method: detect which VERB was actually used

I'm going to create an /api endpoint blindly proxying requests and responses back and forth to the legacy RESTful API system (written in Ruby and hosted on a different domain).

This an intermediary transitional step, so that should just work.

So, I see how that can be easily achieved with app.all(). But as the API is RESTful I do also have to maintain the HTTP verb used for the request - so, can I detect it from the req object? If not, of course I can subscribe 5 handlers for GET, PUT, POST, DELETE, OPTIONS, but it will be much better to avoid this.

Also, how should I deal with the request body (query string and payload)? I assume I'll need to manually recreate the query string from the parsed req.query and pass req.body to request https://github.com/mikeal/request as is - is it right?

like image 615
Guard Avatar asked Oct 18 '12 19:10

Guard


People also ask

What is Express () in js?

Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.

What is Express () function?

Express provides methods to specify what function is called for a particular HTTP verb ( GET , POST , SET , etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response.

What is app use Express JSON ()) in Express?

Using express.json() express. json() is a built in middleware function in Express starting from v4. 16.0. It parses incoming JSON requests and puts the parsed data in req. body .

What does Express Router () do?

The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.


2 Answers

I guess you all need is req.method. And to deal with body, add express.bodyParser() middleware.

like image 187
Anatoliy Avatar answered Oct 17 '22 23:10

Anatoliy


If you just want to pass requests and return the response then you are looking for a proxy.

I'd recommend checking out node-http-proxy. Just load the proxy library, init a proxy, and proxy all requests.

like image 35
jsalonen Avatar answered Oct 18 '22 01:10

jsalonen