axios icon indicating copy to clipboard operation
axios copied to clipboard

Axios gives error when used with localhost

Open rishab2097 opened this issue 2 years ago • 2 comments

Describe the bug

When axios being used to make local http calls it throws error if the url contains localhost and if we replace the local host with the ip address "127.0.0.1" it works

To Reproduce

axios({
    method: 'post',
    url: 'http://localhost:3311/index',
    headers: { 
      'Content-Type': 'application/json'
    },
    data:{}
})

Expected behavior

It should work for both the cases i.e it can take localhost or the ip address

Environment

  • Axios Version [e.g. 0.18.0]
  • Adapter [e.g. XHR/HTTP]
  • Browser [e.g. Chrome, Safari]
  • Browser Version [e.g. 22]
  • Node.js Version [e.g. 13.0.1]
  • OS: [e.g. iOS 12.1.0, OSX 10.13.4]
  • Additional Library Versions [e.g. React 16.7, React Native 0.58.0]

Additional context/Screenshots

Add any other context about the problem here. If applicable, add screenshots to help explain.

rishab2097 avatar Jul 08 '22 15:07 rishab2097

Could you maybe post a screenshot of the error

MichielDeCapThomasMore avatar Jul 10 '22 13:07 MichielDeCapThomasMore

Please check if you have enabled Cross-Origin Resource Sharing(CORS).

CORS definition

If you are using Flask, then you should add CORS

from flask_cors import CORS 

app = Flask(__name__)
CORS(app) 

Similarly in Express.JS

const express = require("express");
const cors = require("cors")
const app = express();

app.use(express.static(path.join(__dirname,"public")));

app.use(cors({
    origin:"*",
    methods:['GET']
}))

After adding CORS, your request will work for both localhost and 127.0.0.1

nkilm avatar Jul 28 '22 18:07 nkilm

Check the solution here https://github.com/axios/axios/issues/3821#issuecomment-1413727575

gitSambhal avatar Dec 12 '23 10:12 gitSambhal