0

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.

4
  • can you log the error in console and get more info about it ? Commented Jul 24, 2017 at 20:49
  • Are you sure the pc is connected to internet ? try to call the same link from browser.. is it working ? Commented Jul 24, 2017 at 21:09
  • 1
    Are you sure your requests using axios/fetch are not cross origin requests? Also, definitely try and log the response to the console, and be sure to check the network request/response from your browser's dev tools, if it's a browser originated request. Commented Jul 24, 2017 at 21:13
  • I fixed it - it was because I was using a cross origin request and the server API (which I wrote) was not equipped to handle it. I've included a code snippet of the fixed code for future reference. Commented Jul 25, 2017 at 2:40

1 Answer 1

1

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) => {
  ...
})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.