Angular 2 Http Post Request添加授权标题

时间:2017-04-19 10:54:52

标签: angular

我有跟随Http请求

var creds = "task_name=" + task + "&duedate=" + taskdate.formatted;

var headers = new Headers();

headers.append('Authorization', localStorage.getItem('token'));
headers.append('Content-Type', 'application/x-www-form-urlencoded');

return this.http.post(myGlobals.API + 'task', creds, {headers: headers })
     .map((response: Response) => {`enter code here`
          console.log(response.json);
      });

获取错误405方法不允许

请让我知道是什么问题

3 个答案:

答案 0 :(得分:1)

尝试以下代码......

  

service.ts

import { User } from '../models/user';
import { Injectable } from '@angular/core';
import { Http, Jsonp, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Config } from '../index';
import { AuthCookie } from '../services/auth-cookies-handler';

@Injectable()
export class UserService {

    constructor(private jsonp: Jsonp, private _http: Http, private _authCookie: AuthCookie) { }

    public jsonHeaders(): Headers {
        let headers: Headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let userInfo: any = JSON.parse(this._authCookie.getAuth());
        if (userInfo)
        {
            headers.append('Authtoken', 'Basic ' + userInfo.authtoken);
        }
        return headers;
    }

    saveUser(user: User): Observable<User> {

        let options = new RequestOptions({ headers: this.jsonHeaders(), method: 'post' });

        let body = JSON.parse(localStorage.getItem('currentUser'));

        return this._http.post(Config.API + 'users', body, options)
                .map((res: Response) => {
                    return res.json();
                })
                .catch(this.handleError);
    }
}

希望这会对你有所帮助。

答案 1 :(得分:0)

试试此代码,包含RequestOptions

import { Http, Response, Headers, RequestOptions } from '@angular/http';

@Injectable()
export class exampleService {
let headers = new Headers();
let requestOptions = new RequestOptions({ headers: headers });

headers.append('Authorization', localStorage.getItem('token'));
headers.append('Content-Type', 'application/x-www-form-urlencoded');

return this.http.post(myGlobals.API + 'task', creds, requestOptions)
     .map((response: Response) => {`enter code here`
          console.log(response.json);
      });
 }

答案 2 :(得分:0)

修复405错误 - 一般 POST方法经常出现405错误。您可能正在尝试在网站上引入某种输入表单,但并非所有ISP都允许使用必要的POST方法来处理表单。

所有405个错误都可以追溯到配置Web服务器以及管理对网站内容的访问的安全性,因此您的ISP应该很容易解释。

http://www.checkupdown.com/status/E405.html