Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

React Native why given cors error in actions when i use django rest framework api on localhost

I am using react native app with api. API coded by django rest framework. I run api in localhost:8000. When i try connect to api with axios i get cors proplem. I added django-cors-header but also it didnt work. Can someone solve it? Thanks.

Frontend/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);
        })

Login.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',
 ....
]

I give this error on chorme: enter image description here

On Network: Network


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're getting a CORS error because the server is emitted a 400 Bad Request before it gets as far as adding the CORS headers.

It isn't clear why it is spitting out Bad Request because you haven't provided any debugging information about that, but it seems likely it has something to do with you claiming 'Content-Type': 'application/x-www-form-urlencoded' when the body is JSON and not form encoded data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...