标头未与ajax请求一起发送

时间:2021-06-19 16:55:31

In my React.js app I use the jquery .ajax method to retrieve info from a backend API. To do this I need to add a authorization token as a header and I added the headers option:

在我的React.js应用程序中,我使用jquery .ajax方法从后端API检索信息。为此,我需要添加一个授权令牌作为标题,我添加了标题选项:

$.ajax({
  url: this.props.source,
  headers: { 'Accept':'application/json', 'Authorization':'Token 36d417' },
  dataType: 'jsonp',
  success: function(data) {
    this.setState({data: data});
  }.bind(this),
  error: function(xhr, status, err) {
    console.error(this.props.url, status, err.toString());
  }.bind(this)
});

But I receive a 401 Unauthorized response from the server. When I check the headers they don't seem to be added?

但我从服务器收到401 Unauthorized响应。当我检查标题时,它们似乎没有被添加?

Remote Address:189.28.154.73:8080
Request URL:https://todos-api.com/api/v1/todos?callback=jQuery1100005772984796203673_1424179650018&_=1424179650019
Request Method:GET
Status Code:401 Unauthorized
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6,nl;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Host:todos-api.com
Pragma:no-cache
Referer:https://todos-reactjs.io/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36

1 个解决方案

#1


4  

Try using the beforeSend callback

尝试使用beforeSend回调

        $.ajax({
              url: this.props.source,
              beforeSend: function (xhr){ 
                xhr.setRequestHeader('Authorization', 'Token 36d417'); 
                xhr.setRequestHeader('Accept', 'application/json'); 
              },
              dataType: 'jsonp',
              success: function(data) {
                this.setState({data: data});
              }.bind(this),
              error: function(xhr, status, err) {
                console.error(this.props.url, status, err.toString());
              }.bind(this)
            });

#1


4  

Try using the beforeSend callback

尝试使用beforeSend回调

        $.ajax({
              url: this.props.source,
              beforeSend: function (xhr){ 
                xhr.setRequestHeader('Authorization', 'Token 36d417'); 
                xhr.setRequestHeader('Accept', 'application/json'); 
              },
              dataType: 'jsonp',
              success: function(data) {
                this.setState({data: data});
              }.bind(this),
              error: function(xhr, status, err) {
                console.error(this.props.url, status, err.toString());
              }.bind(this)
            });