javascript - 我无法在 AXIOS 中发出 GET 请求?
问题描述
为什么我收到此错误 CORS 政策。我在localhost:3000
后台,localhost:5000
我正在通过向 GET 请求从后端服务器获取数据localhost:5000/api/users
。
userAction.js
import { FETCH_USERS } from './types';
import axios from 'axios';
export const fetchUsers = () => dispatch => {
axios.get(`localhost:5000/api/users`)
.then( users =>
dispatch({
type: FETCH_USERS,
payload: users
})
)
.catch( error => {
console.log(error);
});
};
userReducer.js:
import { FETCH_USERS } from '../actions/types';
const initialState = {
items: []
}
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_USERS:
return {
...state,
items: action.payload
};
default:
return state;
}
}
现在我正在向 GET req 发送请求,localhost:5000/api/users
并且我在客户端localhost:3000
上添加了以下代码,server.js
但仍然显示相同的错误。
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
截屏:
解决方案
我上个月遇到了这个问题,这就是我要解决的问题。试试这个后端accpet跨域(我的后端是nodejs):
app.use(function(req, res, next) {
//to allow cross domain requests to send cookie information.
res.header('Access-Control-Allow-Credentials', true);
// origin can not be '*' when crendentials are enabled. so need to set it to the request origin
res.header('Access-Control-Allow-Origin', req.headers.origin);
// list of methods that are supported by the server
res.header('Access-Control-Allow-Methods','OPTIONS,GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, X-XSRF-TOKEN');
next();
});
// 而settop axios默认是这样的。我为客户端使用 React
import axios from 'axios';
const instance = axios.create({
baseURL: 'http://localhost:5000/',
withCredentials: true,
});
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-
urlencoded';
axios.defaults.withCredentials = true;
axios.defaults.crossDomain = true;
export default instance;
推荐阅读
- mqtt - 负载平衡 MQTT 的最佳方式是集群或桥接,以及为什么
- c# - 在 C# 中使用 Graph API 读取 b2c 扩展属性
- sql - Postgres - 如何显示上一年的数据?
- python - 创建聊天机器人时如何解决此错误?
- python - 有没有一种方法可以让命令提示符从 Visual Code Studio 运行 python 文件?
- javascript - 跳过顶级 JSON 数据并通过 JavaScript 检索其下方的数据
- moodle - Moodle 事件层次结构
- reactjs - React TS - 无法在 if 语句中返回正确的组件
- reactjs - 当我将组件连接到商店时,为什么在“连接(应用程序)”的上下文中出现“找不到“商店”错误
- html - 如何在填充边框内圆角图像的角,css