首页 文章

Angular 2 Post:不向服务器发送'content-type: application/json'

提问于
浏览
2

我真的很想在Angular 2中使用POST请求 . 我能够发送带有某些参数的请求,但我的后端(PHP Slim v3)无法获取参数 . 因此,我调查了我的请求,并意识到我的angulr请求发送'content-type:application / text-plain' . 因此我的后端无法访问变量 .

然后,我阅读了很多教程,在这里浏览堆栈溢出并得出结论我必须附加 Headers .

我的角度类看起来像这样:

/**
* Generic method for all POST-requests.
* 
* @author 
* @date 08.01.2017
*/
postData(apiUrl, data): any
{

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let body = JSON.stringify(data)

    return this.http.post(apiUrl, body, options)
        .map((responseData) => 
        {
            if(responseData.status === 200)
            {
                return this.extractData(responseData);
            }
            else
            {
                this.handleRestError(null); 
            }
        })
        .catch(res => {
            return this.handleRestError(res);
       });
}

总而言之,这一切都非常简单 . 但是,当我发送该请求时,奇怪的是,它以某种方式识别出作为OPTIONS请求并给我'不支持的方法:OPTIONS' .

请在此处查看请求 Headers :

OPTIONS /auth/new HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:8100
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:8100/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4

我对后端的回应如下:

HTTP/1.1 200 OK
Host: localhost:8080
Connection: close
X-Powered-By: PHP/5.6.28
Set-Cookie: PHPSESSID=aa546thl9maj7hamjj64vpbe95; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-type: text/plain;charset=UTF-8
Allow: POST
Access-Control-Allow-Methods: OPTIONS
Content-Length: 21

服务器的响应如下所示:

Allowed methods: POST

但是,我设法从服务器获得正确的响应,省略了post请求中的 options 参数 . 然后请求被正确发送,我在Chrome控制台的请求有效负载中看到了所需的参数 . 问题是我可以't get access to the variables on backend, because it keeps giving me a ' content-type:text / plain' .

知道我做错了什么吗?

提前感谢您的帮助!

1 回答

  • 2

    这是因为你面对CORS问题,所以你也需要使用OPTIONS方法(后端) . 这样的事情:

    Access-Control-Allow-Origin: *
    Access-Control-Allow-Methods: GET, POST, OPTIONS
    Access-Control-Allow-Headers: Content-Type
    Access-Control-Max-Age: 86400
    

    在此处了解有关CORS的更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

相关问题