问题描述
我正在使用带有 api 的本机应用程序。由 django rest 框架编码的 API。我在 localhost:8000 中运行 api。当我尝试使用 axios 连接到 api 时,我得到了 cors 问题。我添加了 django-cors-header 但它也不起作用。有人可以解决吗?谢谢。
前端/actions.js
export const loginUser = (username,password)=>dispatch=> {
const body =JSON.stringify({ username,password })
// headers
const config ={
headers:{
'Accept': 'text/html','Content-Type': 'application/x-www-form-urlencoded',// "Access-Control-Allow-Origin": '*'
}
}
const root =API()
console.log(body);
axios.post("http://localhost:8000/api/login/",body,config)
.then(res =>{
dispatch({
type:$AT.LOGIN_USER,payload: res.data
})
}).catch(err=>{
console.log(err);
})
登录.js
const onLoginpressed =() =>{
const usernameError = nameValidator(username.username);
const passwordError = passwordValidator(password.password);
if (usernameError || passwordError) {
setUsername({ ...username,error: usernameError });
setPassword({ ...password,error: passwordError });
}
else{
// console.log("GIRIS YAPILIYOR");
dispatch(loginUser(username.username,password.password));
}
}
API/settings.py
INSTALLED_APPS = [
'django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',# my apps
'account',# third party app
'corsheaders','knox','rest_framework','drf_yasg',]
MIDDLEWARE = [
....
'corsheaders.middleware.CorsMiddleware',....
]
我在 chorme 上给出了这个错误: enter image description here
在网络上: Network
解决方法
您收到 CORS 错误,因为服务器在添加 CORS 标头之前发出了 400 Bad Request
。
不清楚为什么它会吐出错误的请求,因为您没有提供任何关于它的调试信息,但它似乎与您声称 {{1} } 当正文为 JSON 且未形成编码数据时。
,如果你想使用 axios,请配置 IP 地址,你可以检查 ifconfig 并运行 django python manager.py runserver ip: 8000