4
votes

I am using a package called 'concurrently' to run my client and server at the same time on localhost. Client runs on port 3000 while server runs on port 5000. I have set proxy in the package.json of server in the following manner:

"proxy": "https://localhost:5000"

But when I make a request from client in the following manner:

    const config = {
        headers: {
          'Content-Type': 'application/json'
        }
      };

    const res = await axios.post('/api/users', body, config);

It says: POST http://localhost:3000/api/users 404 (Not Found). I don't understand why but despite setting proxy, axios keeps making request to port 3000 instead of port 5000. What is the issue?

4
I had a similar issue, but restart helped in my case :) Kill dev server and npm start or whatever you use.ikos23

4 Answers

3
votes

I just want to say that the solution of adding cors is not a solution. You need to include the proxy "proxy" : "https://localhost:5000" in the package.json, you may need to restart or something or other-- but if you choose to use cors instead, you are allowing anyone to access your API. That means your database is wide open for people to poke around with. Passwords, emails, users, etc. It's all compromised.

1
votes

as far as I understood your question, what you need is to refer Axios developer documents. for time being. check this

import axios, { AxiosInstance } from 'axios';
import * as tunnel from 'tunnel';
   const agent = tunnel.httpsOverHttp({
   proxy: {
     host: 'proxy.mycorp.com',
     port: 8000,
    },
   });
const axiosClient: AxiosInstance = axios.create({
baseURL: 'https://some.api.com',
httpsAgent: agent,
});
0
votes

I got it working correctly. What I did was:

1) change axios.post('/api/users', body, config); to axios.post('http://localhost:5000/api/users', body, config);

2) Then in the 'users' express route on the server side, add CORS functionality by installing 'cors' npm package, and then adding the following lines:

const router = express.Router();
...
// add these lines
var cors = require('cors');
router.use(cors()); 
...
router.post('/', async (req, res) => {
...
});
0
votes

In my case I didn't check well, it appeared that the call was actually forwarded to the api server at the proxy address. Check that the server is running and whether it is receiving your calls or not.