Node.jsサーバーにPOST要求を送信することに奇妙な問題があります。私はGETリスナーもいくつか持っていますが、彼らは完全にうまく動作します。だから、私は以下のようにNode.jsのサーバ(ポート443)に角度2アプリケーション(ポート4200)からの単純な要求を送信しようとしていますが、私はエラーが表示されます。Angular 2クライアントからNode.jsサーバーへのHTTP POST要求
XMLHttpRequest cannot load http://localhost:443/edit_comment . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:4200 ' is therefore not allowed access.
クライアントサービス方法:
(急行ライブラリー付き)public saveComment(id: number, comment: string) : Observable<Response> {
let data = { id: id, comment: comment };
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:443/edit_comment', JSON.stringify(data), options)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
とのNode.jsサーバ側:
app.post('/edit_comment', (req, resp) => {
console.log('blabla') //this log never displays
resp.setHeader('Access-Control-Allow-Origin','*')
resp.send(JSON.stringify('foo'))
});
問題は、それが思われることですconsole.logは 'blabla'メッセージを画面に表示しないので、app.postコールバック関数は呼び出されません。
ここでは、私のブラウザで開発者ツールからもリクエストおよびレスポンスヘッダいる:
リクエストヘッダ:
Accept:*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:443
Origin:http://localhost:4200
Pragma:no-cache
Referer:http://localhost:4200/testlinemonitor
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
レスポンスヘッダ:
HTTP/1.1 200 OK
X-Powered-By: Express
Allow: POST
Content-Type: text/html; charset=utf-8
Content-Length: 4
ETag: W/"4-oCQ57CKdi+DnSwwWAjkjEA"
Date: Fri, 10 Mar 2017 12:49:41 GMT
Connection: keep-alive
よろしく
プリフライトリクエストOPTIONS/edit_commentはPOSTを呼び出す前に、として適切なヘッダを送信するように設定する必要があります/ edit_commentブラウザは、「OPTIONS/edit_comment [の –
可能な複製を呼び出します。
てみCORS要求を許可し、このヘッダを追加します要求されたリソースに「Access-Control-Allow-Origin」ヘッダーが存在しません」(http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-リクエストされたリソース) – georgeawg