Angular 2 http POST请求

时间:2016-06-26 19:01:14

标签: angular http-post

我是Angular 2的新手,目前我正在尝试编写一个小型Web应用程序而且我有点卡住了。我需要做一个帖子请求,我有以下Python代码(我在这里替换了参数,但它完全正常):

import requests
url = "https://somerandomlink.wasd"
payload = "{\n    \"var1\":{\n        \"var1Text\" : \"parameter\"\n    }\n}"
headers = {
    'authorization': "Basic somethingsomethinghidden",
    'x-synctimeout': "30",
    'accept': "application/json",
    'cache-control': "no-cache",
    'content-type': "application/json"
    }
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)

我想用Angular 2做同样的事情,但由于某些原因我的Angular 2代码不起作用:

import {Component, enableProdMode, Injectable, OnInit} from '@angular/core';
import {Http, Headers, HTTP_PROVIDERS, URLSearchParams} from '@angular/http';
import "rxjs/add/operator/map";
@Injectable()
class HTTPService{

    constructor (private http: Http) {}

    test(){ 
        var params = JSON.stringify({ var1: { var1Text: 'parameter' } });

        var headers = new Headers(); 
        headers.append('Authorization','Basic somethingsomethinghidden');
        headers.append('X-SyncTimeout','30');
        headers.append('Accept','application/json');
        headers.append('Cache-Control','no-cache');
        headers.append('Content-Type','application/json');
        return this.http.post('https://somerandomlink.wasd',params,{headers: headers})

    }
}
@Component({
    selector: 'home',
    templateUrl: 'app/html/some.component.html',
    providers: [HTTP_PROVIDERS, HTTPService]
})
export class someComponent {
    question = '';
    view_question = '';
    view_answer = '';


    constructor(private httpService: HTTPService){}


    eventHandler(key) {
        if (key==13){
            this.view_question = this.question;
            this.reqAns(this.question);
            this.question = '';
        }
    } 

    reqAns(question){
        if (question == ''){ 
            return ''
        }else{
            this.httpService.test().map(res => res.json()).subscribe(
                data => this.view_answer = "DATA block: " + JSON.stringify(data),
                error => this.view_answer = "ERROR block: " + JSON.stringify(error),
                () => console.log('finished')
            );

        }
    }

}

它产生以下输出:

ERROR block: {"_body":{"isTrusted":true},"status":200,"ok":true,"statusText":"Ok","headers":{},"type":3,"url":null}

如果有人能帮助我,我真的很感激。应该没有语法错误,因为我已经尝试了基于视频教程的另一个帖子请求(更容易的一个,使用urlencoded格式)并且它有效。所以问题必须是别的,虽然我不知道是什么。

其他信息:

信息A:

以下方法,正如我所提到的,基于视频教程工作并产生预期的输出:

postJSON_tutorial(){
    var json = JSON.stringify({var1: 'test', var2: 3, var3: "asdas"});
    var params = 'json=' + json;
    var headers = new Headers();
    headers.append('Content-Type','application/x-www-form-urlencoded');
    return this.http.post('http://validate.jsontest.com',params,{headers: headers})
}

具有以下正确输出

DATA block: {"object_or_array":"object","empty":false,"parse_time_nanoseconds":116419,"validate":true,"size":3}

信息B:

由于有人要求提供版本,这里是整个package.json

{
  "name": "webapp",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common":  "2.0.0-rc.1",
    "@angular/compiler":  "2.0.0-rc.1",
    "@angular/core":  "2.0.0-rc.1",
    "@angular/http":  "2.0.0-rc.1",
    "@angular/platform-browser":  "2.0.0-rc.1",
    "@angular/platform-browser-dynamic":  "2.0.0-rc.1",
    "@angular/router":  "2.0.0-rc.1",
    "@angular/router-deprecated":  "2.0.0-rc.1",
    "@angular/upgrade":  "2.0.0-rc.1",
    "systemjs": "0.19.27",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "angular2-in-memory-web-api": "0.0.9",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings":"^0.8.1"
  }
}

0 个答案:

没有答案