单击按钮后,我尝试在 React 组件中运行以下命令:
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)
})
}
当我在 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)
})
但是当我单击按钮后调用它时,我收到一条警报,显示“错误:网络错误”。我尝试使用 fetch() 运行它,而不是不使用 CORS,但我得到的是空响应,而不是包含数据的响应。
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)
})
我尝试使用其他 API(例如 api.github.com
)运行此程序,但得到了相同的结果。它可以在 Node 中运行,但不能在 React 中运行。
最佳答案
经过几个小时的艰苦努力,我终于发现我的服务器出了什么问题。它无法处理 CORS。之前的代码看起来像这样:
var express = require('express')
var app = express()
app.get('/', (req, res) => {
...
})
结果我只需要启用 cors 即可。运行 npm install cors
并将服务器代码更改为:
var express = require('express')
var app = express()
var cors = require('cors')
app.use(cors())
app.get('/', (req, res) => {
...
})
关于javascript - React中调用axios导致网络错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45289691/