首页 文章

Angular2标头未正确设置

提问于
浏览
1

我正在使用angular2 http做一个简单的帖子请求 .

问题是它没有正确设置 Headers . 我得到的就是这个,而不是设置内容类型和授权

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:authorization, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.joinmunch.com
Origin:http://localhost:8100
Referer:http://localhost:8100/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36

这是我的代码

let bodyString = JSON.stringify(user); // Stringify payload
    let headers      = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
    headers.append('Authorization', 'bearer MY_AUTH_TOKEN');

    let options       = new RequestOptions({ headers: headers }); // Create a request option
    options.withCredentials = true;

    return this.http.post(this.baseUrl + 'customer/register', bodyString, { headers: headers }) // ...using post request
                         .map((res:Response) => res.json()) // ...and calling .json() on the response to return data
                         .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if an

这是响应标头

HTTP/1.1 401 Unauthorized
Server: nginx
Date: Fri, 14 Oct 2016 16:03:36 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept

screen shot of request and response

1 回答

  • 0

    这只是CORS预检请求,而不是实际请求 . 您可以告诉我们将根据实际请求设置标头

    Access-Control-Request-Headers:authorization, content-type
    

    预检请求询问服务器是否接受 content-typeauthorization 标头,这些标头是您设置的标头

    如果您不了解CORS,请查看链接 . 也许它可以帮助您解决任何您可能遇到的实际问题,因为问题不在于未设置标头 .

相关问题