I am having problem using http-proxy-middleware - node.js

I have two servers running in my backend, because of that I have to use the http-proxy-middleware package but I am encountering some problems.
This is my code in the frontend which is running on localhost:3000
axios("/api2/login",data)
.then((res) => {
});
This is my code in the backend which is running on localhost:5001
const { createProxyMiddleware } = require('http-proxy-middleware');
app.use(createProxyMiddleware('/api2', {target: 'http://localhost:5001', changeOrigin: true}))
app.post("/login", (req, res, next) => {
res.send("Logged In");
});
This code is no working showing this error in the browser's console
GET http://localhost:3000/api2/login 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)
I am not able to understand where I am going wrong.

Looks like it's hitting localhost:3000 instead of localhost:5001 which is where your server is running from.
axios("http://localhost:5001/api2/login",data)
.then((res) => {
});
You can also set the baseURL in axios. HTTP get request with Axios gets sent with the local host IP at the beginning of the URL

If I understand correctly your server is listening on port 5001. So, you need to proxy your requests from 3000 to 5001. You can do that in the react application by setting the proxy value in package.json:
"proxy": "http://localhost:5001",
For more information about this subject, check the docs.
Edit for the configuration explained in the comment section
First in package.json:
"proxy": "http://localhost:5002",
Create a new server (proxyserver) which will be listening in port 5002:
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
// redirection for first server 5000
app.use('/api1', createProxyMiddleware({ target: 'http://localhost:5000', changeOrigin: true }));
// redirection for second server 5001
app.use('/api2', createProxyMiddleware({ target: 'http://localhost:5001', changeOrigin: true }));
app.listen(5002);
For the other servers (5000 and 5001) you don't need to redirect the requests. Just make sure they're listening on the right ports (5000 and 5001), for example:
const express = require('express');
const app = express();
app.post("/api2/login", (req, res, next) => {
res.send("Logged In");
});
app.listen(5001);

I followed the steps mentioned in this post along with some changes,
I changed my Axios request code to:
axios({
method: "POST",
data: user,
withCredentials: true,
url: "/api2/login",
}).then((res) => {})
Otherwise, the proxy server was treating it as a GET request.
Secondly, I changed the proxy endpoint code int the proxy server as:
app.use('/api2', createProxyMiddleware({
target: 'http://localhost:5001',
changeOrigin: true,
pathRewrite: {
[`^/api2`]: '',
},
}));
Further information about the proxy endpoint change can be found here.

Related

How do you use devServer.proxy in Vue?

I'm currently trying to proxy my requests from my Vue app so I can send cookies back from the server that exists separate from my frontend.
I have my frontend on port 8080 and server on port 3000. However, when I try to configure my proxy to use port 3000 in Vue using devServer.proxy, it sends the request to 8080 still.
Here is my code in vue.config.js:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'https://localhost:3000',
ws: true,
changeOrigin: true
}
}
}
}
Here is my axios request:
axios.post(`/api/auth/login/`, loginDetails, {
withCredentials: true,
credentials: 'include'
})
.then(function (response) {
console.log('login response: ', response)
})
.catch(error => {
console.error(error)
});
Here is the error I get that shows the frontend is still sending to 8080:
I also tried using the following in vue.config.js and not having anything prefixed to the request url, but to no avail.
module.exports = {
devServer: {
proxy: 'http://localhost:3000'
}
}
Here is the documentation that I am using https://cli.vuejs.org/config/#devserver
Solution:
After taking a look at the server logs, I found out that the proxy was working and it was trying to find the /api/auth/login route on my server. However, I only had /auth/login so the server sent the 404 status.
I'm not sure if this is the correct way to do this, but I simply prepended the server route with /api and it worked like so:
app.use('/api/auth', authRouter)
Previously it looked like this:
app.use('/auth', authRouter)
Thank you to Estus Flask for the tips in the comments.

http proxy middleware not working with create-react-app

This is my middleware file known as setupProxy.js.
I have my express server running on port 5000, I also have my app using '/todos';
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
console.log('Proxy setup');
app.use(
'/testing',
createProxyMiddleware({
target: 'http://localhost:5000/todos',
changeOrigin: true,
})
);
};
I do an api call
await axios.get('/testing/home', {validateStatus: false})
.then(async (response) => {
}
This throws an error
GET http://localhost:5000/testing/home 404 (Not Found)
Why is my proxy not pushing /testing/home to localhost:5000/todos/home?
I have the setupProxy.js file in the src folder, the package json is separated from my servers package.json file. Am I supposed to proxy from the backend instead of the front-end or something? I can get all normal requests for /todos/* from my front-end so it just seems like the proxy isnt working at all.

getting CORS and network error while calling axios post request using Vue js

I am getting error while calling axios post request. But it works properly on postman.
The code I used for calling the request is
methods : {
displayData(){
var config = {
method: 'post',
url: 'http://localhost:5000/api/request/displayRequest',
headers: {
'Content-Type': 'application/json'
},
data : JSON.parse(JSON.stringify(this.user._id))
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
},
async mounted(){
this.displayData()
}
I have already implemented CORS on the back-end in server.js
// Cors Middleware
const cors = require('cors');
app.use(cors());
app.options("*", cors());
app.use(
cors({
origin: (origin, callback) => callback(null, true), // you can control it based on condition.
credentials: true, // if using cookie sessions.
})
);
in your backend use this :
npm i cors
and in your express backend entrypoint:
const cors = require("cors");
app.use(cors());
app.options("*", cors());
You are running your front-end on localhost and using some port. Also, your back-end is running on localhost, port 5000. But your front-end application can not access any other port due to CORS policy. You can solve this problem in the back-end if you are using Node JS.
Install cors by the following command:
npm i cors
Then on your server file, change your app by
app.use(cors());
N.B. If you used React js, you could use http-proxy-middleware. Just create a file inside the src directory named "setupProxy.js". and add the following lines.
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
"/api",
createProxyMiddleware({
target: "http://localhost:5000/",
})
);
};
Don't forget to change the port in this file into the port of your server.

How to fix "Response to preflight request doesn't pass access control check: It does not have HTTP ok status" error in react app with nodejs api

I have been trying to do an api call (nodejs with express running on localhost) from a react app running in the browser over a local dev server (web-pack dev server). Everything was working well until I tried to call the api. They are both running on separate ports.
I have tried adding the cors headers (Recommended by MDN) to both the post call (from the app in browser) and to the response from the Nodejs API but neither of these solved the issue.
Code for the api call (in browser):
const headers = {
'Content-Type': 'application/json',
'access-token': '',
'Access-Control-Allow-Origin': '*',
}
export default async () => {
try {
const body = JSON.stringify({
test: true,
})
const response = await fetch('http://localhost:1337/internal/provider/check_email_exist', {
method: 'POST',
headers,
body,
})
console.log(response)
} catch (e) {
return e
}
}
API Middleware (in nodejs):
// Verify All Requests
app.use(VerifyToken)
// Compress
app.use(compression())
// Helmet middlware
app.use(helmet())
// Body Parser
app.use(bodyParser.urlencoded({
extended: false,
}))
app.use(bodyParser.json())
The expected result is to just give a 200 status code and respond with the data.
The actual output is:
OPTIONS http://localhost:1337/internal/provider/check_email_exist 404 (Not Found)
Access to fetch at 'http://localhost:1337/internal/provider/check_email_exist' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Since you're using webpack-dev-server you can use the proxy option DevServerProxy.
Your configuration will look like this:
// webpack.config.js
devServer: {
proxy: {
'/internal': 'http://localhost:1337'
}
}
Since I can't see your express routes on your question I'm speculating about the proxy route if your API lives on /internal endpoint then you should modify your React code like this:
const response = await fetch('/internal/provider/check_email_exist', {
method: 'POST',
headers,
body,
})
As you can see I ommited the https://localhost:1337 because the proxy option from webpack-dev-server will handle this and it will redirect to http://localhost:1337. Hope this will help you. Cheers, sigfried.
EDIT
As the comment on your question pointed out you should set the headers on your express server, not the client, for this task you can use the cors-middleware package.
Maybe this can help if you face with preflight errors.
My full config:
const cors = require('cors');
const express = require('express');
const { createProxyMiddleware: proxy } = require('http-proxy-middleware');
...
const logLevel = 'info';
const ip = require('ip').address();
const proxyOptions = {
xfwd: true,
target,
changeOrigin: true,
logLevel,
cookieDomainRewrite: {
'*': 'localhost',
},
headers: {
'X-Forwarded-For': ip,
'X-Node': 'true',
},
};
const backNginxApp = express();
backNginxApp.use(
cors({
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
origin: 'http://localhost:3000',
optionsSuccessStatus: 200,
credentials: true,
})
);
backNginxApp.use('/api', proxy(proxyOptions));
API: const target = 'https://someapi.com'
Local development running at: http://localhost:3000

Proxy in package.json not affecting fetch request

I am trying to fetch some data from the development server using React.
I am running the client on localhost:3001 and the backend on port 3000.
The fetch request :
const users = fetch('/api/users');
users.then((err,res) => {
console.log(res);
})
When I run my development server and webpack-dev-server I get the following output:
GET http://localhost:3001/api/users 404 (Not Found)
I tried specifying the proxy in the package.json so it would proxy the request to the API server, however nothing has changed.
Here is my package.json file:
.. and the webpack.config :
Please tell me, if you need to see anything else from my project. I apologies, if I'm missing something and not being thorough, I'm still quite new to using these technologies.
You can modify your fetch request API url to give the complete hostname since
fetch('http://localhost:3000/api/users')
also make sure that you have CORS enabled on your backend
In case your want to redirect through webpack, your can try devServer.proxy as
devServer: {
inline: true,
contentBase: './dist',
port: 3001,
proxy: { "/api/**": { target: 'http://localhost:3000', secure: false } }
}
I know I'm a little late to the game here, but I'll leave it here for future reference.
To make the devServer proxy work as expected, you need to specify the HTTP Accepts header to be something else than "text/html". Do this with the init-object that fetch accepts as the second argument. A simple example:
fetch("/api/profile",{
headers:{
"accepts":"application/json"
}
})
.then(res => {
console.log(res);
return res.json();
})
.then(json => console.log(json) )
.catch( a => { console.log(a) });
The reason for this is that the WebPack Dev Server normally uses a context/namespace to differentiate between what to serve and what to forward. The create-react-app scripts do not extract a namespace from the proxy path in the package.json file. Instead the scripts has the opinionated default behaviour that any request using something else than HTTP GET will get forwarded. Also, anything using HTTP GET, but NOT text/html as the Accepts header will get forwarded.
The reasoning is because most React Apps are SPA (Single Page Applications) which use AJAX/Fetch to communicate with some API. API's normally use JSON or XML, but not text/html.
In the package.json
"proxy": {
"/api/users": {
"target": "http://localhost:3000"
}
},
I had the same problem using axios and was only able to get it working by using the complete hostname and enabling Cors.
const response = await axios.get('http://localhost/users/');
Install cors
npm i cors
Use cors
const express = require("express");
const request = require("request");
const cors = require("cors");
const app = express();
app.use(cors());
app.use("/", (req, res) => {
//...
});
app.listen(80, () => {
console.log("CORS-enabled web server listening on port 80");
});
Ref
The solution by user jellyfish-tom in https://github.com/webpack/webpack-dev-server/issues/793#issuecomment-316650146 worked for me.
devServer: {
proxy: {
"*": "http://[::1]:8081"
// "secure": false,
// "changeOrigin": true
}
},
Webpack Dev Server uses devServer.proxy config in your Webpack config to control proxying requests.

Resources