gpt4 book ai didi

Angular 2,Http 和不设置内容类型 "application/json"

转载 作者:太空狗 更新时间:2023-10-29 18:07:27 25 4
gpt4 key购买 nike

我正在尝试在服务中使用 Angular 2(2.0.0-rc.1) 执行一个简单的检查登录方法。当我尝试将内容类型设置为 application/json 时,它在发送到我的 web api 后端时从不设置 header 。

import { Injectable } from '@angular/core';
import { HTTP_PROVIDERS, Http, Response, Headers, RequestOptionsArgs, RequestMethod, Request, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Other Modules Left out for Security } from 'Hidden';

@Injectable()
export class LoginService {

private _http: Http;


constructor(http: Http) {
this._http = http;


}

CheckLogin(model: CredentialModel) {

let url = 'http://localhost:51671/api/Login';

let data = JSON.stringify(model);

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');


let requestOptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: headers,
body: data
});


console.log(requestOptions);
console.log(data);

return this._http.post(url, data, requestOptions);

}
}

Web API 请求

OPTIONS /api/Login HTTP/1.1
Host: localhost:51671
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:5616
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2754.0 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
DNT: 1
Referer: http://localhost:5616/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

使用 PostMan 使用完全相同的数据效果很好!看起来 Angular 2 使用 POST 方法发送 application/json 有问题。

解决此问题的任何帮助都会有所帮助。乐于尝试任何建议。

最佳答案

Http 类的 post 方法接受类型为 RequestOptionsArgs 而不是 RequestOptions 的对象。

class RequestOptionsArgs {
url : string
method : string | RequestMethod
search : string | URLSearchParams
headers : Headers
body : any
withCredentials : boolean
}

您可以在第三个参数中按字面意思指定它:

return this._http.post(url, data, { headers: headers });

关于Angular 2,Http 和不设置内容类型 "application/json",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37595980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com