get('/info', (req, res, next) => { res.send('This is a proxy service which proxies to Billing and Account APIs.'); }); Before defining the proxy endpoints, let's also add a simple authorization management middleware that throws the 403 (Forbidden) error if the authorization header is missing: JavaScript Copy the code // Authorization app.use('', (req, res, next) => { if (req.headers.authorization) { next(); } else { res.sendStatus(403); } }); Next, we define the proxy endpoint. We want to use the proxy for all requests starting with /json_placeholder to the famous JSONPlaceholder API (a simple mock API that contains multiple endpoints that support all HTTP methods).
We also define a pathRewrite so that /json_placeholder is omitted when telegram philippines girl passed to the API: JavaScript Copy the code // Proxy endpoints app.use('/json_placeholder', createProxyMiddleware({ target: API_SERVICE_URL, changeOrigin: true, pathRewrite: { [`^/json_placeholder`]: '', }, })); So when we send a request to localhost:3000/json_placeholder/posts/1 , the URL is rewritten to <API_SERVICE_URL>/posts/1 ( in this case: /posts/1) , thus removing /json_placeholder which the API doesn't need. Finally, we start the configured server with this function call: JavaScript Copy the code // Start the Proxy app.listen(PORT, HOST, () => { console.log(`Starting Proxy at ${HOST}:${PORT}`); }); Run the proxy Let's start the proxy with the following command: Bash Copy the code yarn start You should get an output similar to the following: Bash Copy the code yarn run v1.
22.4 $ node index.js [HPM] Proxy created: / - [HPM] Proxy rewrite rule created: "^/json_placeholder" ~> "" Starting Proxy at localhost:3000 The proxy should now be running and if we open a second terminal and send a GET request to /info : Bash Copy the code curl localhost:3000/info We should receive a response from our proxy. And, unsurprisingly, we have: Text Copy the code This is a proxy service which proxies to JSONPlaceholder API. OK, that's great, but we don't want to receive annoying GET endpoints, we want to use the proxy! To test the proxy, we can send a new GET request as follows: Bash Copy the code curl localhost:3000/json_placeholder/posts/1 the man says oh no Oh, no! This returns: Text Copy the code Forbidden Don't worry, this is what we expected, because we included the authorization middleware that requires every request to contain an authorization header.
endpoints that support all HTTP methods).
-
- Posts: 10
- Joined: Sun Dec 22, 2024 5:33 am