Django Rest Framework CORS blocking XMLHttpRequest

不羁的心 提交于 2019-12-23 02:29:27

问题


I have set up my CORS policy using Django-cors-headers with the following settings:

APPEND_SLASH=False
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'localhost:8000',
    'localhost:3000',
    'localhost'
)

I have also added it to installed_apps and middleware.

Now I am making a React app for the front end and using AXIOS for my API requests. When I make an API request to log in to my app the CORS policy allows it. But, if I make an API request that requires a Token, I get:

Access to XMLHttpRequest at 'localhost:8000/api/TestConnection/' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

It seems that I need to allow XMLHttpRequest for supported protocol schemes but I cannot find anything in the pypi documentation about this.

EDIT: Here is the AXIOS Request:

axios.post("localhost:8000/api/TestConnection/",
    {headers:
      {
          'Authorization': "Bearer " + localStorage.getItem('JWTAccess')
      }
    },
    { 
      testString: 'Hello API'
    })
    .then(response => {
      console.log(response)
      })
    .catch(error => {
      console.log(error);
})

Thank you!


回答1:


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.




回答2:


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'
)



回答3:


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/



来源:https://stackoverflow.com/questions/55108410/django-rest-framework-cors-blocking-xmlhttprequest

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