我使用Express js作为服务器,并部署到Heroku,客户端使用使用Axios的React native (Expo)网络,我的问题是当我使用Postman和本地浏览器请求api时,它工作得很好,但当我使用axios请求api时,显示Network Error
Network Error
- node_modules/axios/lib/core/createError.js:15:17 in createError
- node_modules/axios/lib/adapters/xhr.js:88:22 in handleError
- node_modules/event-target-shim/dist/event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:575:10 in setReadyState
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:389:6 in __didCompleteResponse
- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue这是my react原生请求api
useEffect(() => {
axios.get('http://myapp.herokuapp.com/member-test', {
headers:{
"Content-Type": "application/json",
'Accept': 'application/json',
},
})
.then(res => {
alert(res)
const categories = res.data;
console.log("Sukses");
})
.catch(function (response) {
console.log(response)
alert(response.message)
})
}, []);和我的服务器端
const app = express();
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var corsOptions ={
origin : true,
credentials: true,
exposedHeaders: ['Content-Length', 'X-Foo', 'X-Bar'],
optionsSuccessStatus : 200
}
app.use(cors({corsOptions}));
app.get('/member-test', (req, res) => {
res.send('Api Live');
});
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});我不知道问题出在哪里,这几天我被困住了,我真的需要帮助来解决这个问题
发布于 2021-07-18 04:53:07
您正在将corsOptions作为对象传递给cors中间件,请尝试更改此行
app.use(cors({corsOptions}));在这里
app.use(cors(corsOptions));希望它能对你有所帮助。
https://stackoverflow.com/questions/63763424
复制相似问题