PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How to set proxy when using axios to send requests?

 October 13, 2022     axios, express, node.js, reactjs     No comments   

Issue

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?


Solution

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) => {
...
});


Answered By - Tarun Khare
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing