Http post with angular 2,cant set post on post

时间:2016-05-18 21:39:39

标签: angular

在角度2中得到了这个:

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

this.http.post('http://localhost:3007/api_jira/login', body, options).subscribe(...

我需要在后端保存会话。当我从邮递员那里运行时它起作用。但是当我从角度发布时,后端不会设置会话。

为什么我需要在帖子中设置选项?我的IDE说它是可选的吗?无论如何,我可能需要在标题中插入一些设置以允许存储会话。有什么想法吗?

更新 这是我的邮递员要求卷曲:

curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: c730242e-0497-7344-35b1-f0addca9e7b6" -d '{"host":"xxx","basic_auth":{"username":"xxx","password":"xx"}}' "http://localhost:3007/api_jira/login"

这是来自chrome dev工具,网络,标题标签的信息:

Request URL:http://localhost:3007/api_jira/login
Request Method:POST
Status Code:200 OK
Remote Address:[::1]:3007
Response Headers
view parsed
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Vary: X-HTTP-Method-Override
Content-Type: application/json
set-cookie: connect.sid=s%3AM04ERSgj6F-5wKHwX1XY3G8CO6ZqfEHX.Xflr7ueknyg%2FYHvHIDqBp4ogfddfVdRwJS7GV4bniMk; Path=/; Expires=Thu, 19 May 2016 08:17:58 GMT
Date: Thu, 19 May 2016 08:16:58 GMT
Connection: keep-alive
Content-Length: 0
Request Headers
view parsed
POST /api_jira/login HTTP/1.1
Host: localhost:3007
Connection: keep-alive
Content-Length: 89
Pragma: no-cache
Cache-Control: no-cache
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
Content-Type: application/json
Accept: */*
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate
Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4,ca;q=0.2,nb;q=0.2
Request Payload
view parsed
{"host":"xx.atlassian.net","basic_auth":{"username":"xx","password":"xx"}}

Chrome帖子转换为curl:

curl 'http://localhost:3007/api_jira/login' -H 'Pragma: no-cache' -H 'Origin: http://localhost:4200' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4,ca;q=0.2,nb;q=0.2' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36' -H 'Content-Type: application/json' -H 'Accept: */*' -H 'Cache-Control: no-cache' -H 'Referer: http://localhost:4200/' -H 'Connection: keep-alive' --data-binary '{"host":"xx.atlassian.net","basic_auth":{"username":"xx","password":"xx"}}' --compressed

这是我的后端(节点),我在我的会话中尝试一些数据(jiraConfig):

server.post('/api_jira/login', function(req, res){
    var jiraConfig = req.body;
    checkIfJiraConfigIsValid(jiraConfig, function(error, resp){
      if(error){
        res.status(401).send('Not authorized')
      }else{
        req.session.jiraConfig = jiraConfig;
        res.status(200).send();
      }
    })
  });

1 个答案:

答案 0 :(得分:0)

可能的问题是您忘记导入Headers类,因此请求中未设置Content-Type标头,服务器无法对您的有效负载进行反序列化。< / p>

import { Headers, ... } from '@angular/http';