Django Rest Framework CORS blocking XMLHttpRequest

删除回忆录丶 提交于 2019-12-08 04:42:28

I Have had a similar issue with a ReactNative app which was happening due to ReactNative using IP 10.0.2.2 for localhost (I do not remember the details or why). I solved it by adding to my class.

  componentWillMount() {
    axios.defaults.baseURL = 'http://10.0.2.2:8000/api/';
    axios.defaults.timeout = 1500;
  }

I do not know if this is the right IP but may be worth looking at.

EDIT

handleRequest() {
    const payload = { username: this.state.username, password: this.state.password } 
    axios
      .post('login/', payload)
      .then(response => {
        const { token, user } = response.data;

        // We set the returned token as the default authorization header
        axios.defaults.headers.common.Authorization = `Token ${token}`;

        // Navigate to the home screen
        Actions.main();
      })
      .catch(error => {
            console.log(error)
      });
}

By saving the Token within my headers it is always sent.

The error says "from origin 'http://localhost:3000'" and to "check the cors policy"

I see your CORS policy is

CORS_ORIGIN_WHITELIST = (
    'localhost:8000',
    'localhost:3000',
    'localhost'
)

maybe try providing the full http url. so

CORS_ORIGIN_WHITELIST = (
    'localhost:8000',
    'http://localhost:3000',
    'localhost'
)

I solved it! The solution was very simple(of course),

For the request I needed to use part of @HenryM 's solution.

First I needed to establish the default url:

axios.defaults.baseURL = 'http://127.0.0.1:8000/api/';

Then I save the payload and header to const variables:

const header = {
  headers:{
    'Authorization': "Bearer " + localStorage.getItem('JWTAccess')
  }
}
const payload = {
  testValue: "Hello API"
}

Finally, the main issue was that my parameters were in the wrong order:

axios.post("TestConnection/", payload, header)
    .then(response => {
      console.log(response)
      })
    .catch(error => {
      console.log(error);

Apparently the propper order, at least when using Django Rest Framework, is payload then header!!!

Thank you to everyone who tired to help! This was the article that ended up helping me: https://www.techiediaries.com/django-vuejs-api-views/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!