簡體   English   中英

從Angular 2客戶端到Node.js服務器的HTTP POST請求

[英]HTTP POST request from Angular 2 client to Node.js server

將POST請求發送到我的Node.js服務器時遇到一個奇怪的問題。 我也有一些GET偵聽器,但它們工作得很好。 所以,我試圖按照以下方式從Angular 2應用程序(端口4200)向Node.js服務器(端口443)發送一個簡單請求,但我收到一個錯誤:

XMLHttpRequest無法加載http:// localhost:443 / edit_comment 對預檢請求的響應未通過訪問控制檢查:請求的資源上不存在“ Access-Control-Allow-Origin”標頭。 因此,不允許訪問源' http:// localhost:4200 '。

客戶服務方式:

   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回調函數。

在這里,您還可以從瀏覽器中的開發人員工具獲得Request和Response標頭:

請求標頭:

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調用。 如果您有跨源請求,則瀏覽器將始終執行預檢OPTIONS調用。 然后,如果成功,它將執行GET或POST。 請在Chrome調試器中檢查網絡流量。

這是ExpressJS服務器的軟件包https://github.com/expressjs/cors

您不僅需要允許允許的來源,還需要允許的方法和標頭。

嘗試添加以下允許CORS請求的標頭:

res.setHeader('Access-Control-Allow-Origin', '*')

//Add as many Headers as you want to line below
//If you use "Authentication" Header, insert it like 'Content-type, Authentication'
res.setHeader('Access-Control-Allow-Headers', 'Content-type')

res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM