user3806019
user3806019

Reputation: 45

Calling Axios in React results in Network Error

I'm trying to run the following command in a React component after clicking a button:

import axios from 'axios'    
export function callApi(index, callback) {

axios.get('http://localhost:8080/search?index=120&json=true&all=true')
    .then(res => {
        alert(res)
    })
    .catch((error) => {
        alert("error: " + error)
    })

}

It works fine when I'm running the code in node,

var axios = require('axios')
axios.get('http://localhost:8080/search?index=120&json=true&all=true')
    .then(res => {
        alert(res)
    })
    .catch((error) => {
        alert("error: " + error)
    })

But when I call it after clicking a button, I get an alert that says "Error: Network Error." I've tried running it with fetch() instead with no CORS either, but I'm getting an empty response instead of one with data.

fetch('http://192.168.1.156:8080/search?index=120&json=true&all=true', {mode: 'no-cors'})
    .then(res => {
        alert(res)
    })
    .catch((error) => {
        alert("error: " + error)
    })

I've tried running this with other APIs like api.github.com but I get the same result. It works in node, but not React.

Upvotes: 0

Views: 5263

Answers (1)

user3806019
user3806019

Reputation: 45

After several grueling hours, I finally found what was wrong with my server. It was not able to handle CORS. The code looked like this before:

var express = require('express')
var app = express()
app.get('/', (req, res) => {
  ...
})

Turns out I just had to enable cors. It works after running npm install cors and changing the server code to:

var express = require('express')
var app = express()
var cors = require('cors')

app.use(cors())
app.get('/', (req, res) => {
  ...
})

Upvotes: 1

Related Questions