Reputation: 1
I am trying to use http-proxy-middleware in NodeJs. It is not working. I am working on node version 18.
const express = require('express');
const router = express.Router();
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const PORT = 6001;
const HOST = "localhost"; //tried with 127.0.0.1 also
const API_URL = "https://jsonplaceholder.typicode.com/posts";
const proxyOptions = {
target: API_URL,
changeOrigin: true,
pathRewrite: {
[`^/api/posts/all`]: '',
},
}
router.get('/all',createProxyMiddleware(proxyOptions));
app.listen(PORT, HOST, () => {
console.log(`Proxy Started at ${HOST}:${PORT}`)
});
I am trying endpoint http://localhost:6001/api/posts/all and getting this issue Cannot GET /api/posts/all
Upvotes: 0
Views: 1155
Reputation: 102587
The API for listing all posts is /posts
, not /posts/all
.
An working example
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const PORT = 6001;
const HOST = "localhost";
const API_URL = "https://jsonplaceholder.typicode.com";
const proxyOptions = {
target: API_URL,
changeOrigin: true,
pathRewrite: {
[`^/api`]: '',
},
}
app.use(createProxyMiddleware(proxyOptions));
app.listen(PORT, HOST, () => {
console.log(`Proxy Started at ${HOST}:${PORT}`)
});
When access the http://localhost:6001/api/posts
endpoint, the logs:
[HPM] Proxy created: / -> https://jsonplaceholder.typicode.com
[HPM] Proxy rewrite rule created: "^/api" ~> ""
Upvotes: 0