-1

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

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197

2 Answers2

0

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

if you want to work with axios please configure with IP address you can check ifconfig and run django python manager.py runserver ip: 8000