如何在角度2中设置beforesend标题

时间:2017-03-18 09:32:27

标签: angular xmlhttprequest

我是angular2的新手。我想使用angular2.Ajax请求创建一个http帖子同样的is-

 $.ajax({
    url: apiUrl,
    type: 'Post',
    dataType: "json",
    data: request,   
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization-ApiKey", 'Ak12mr27Xwg@d89ul');
    },
    success: function (response) {
        if (response.ErrorCode != 0) {
           alert(response.ErrorMessage)
        }
        else {
        }
    },
    error: function (a) {
        alert('Invalid Action.');
       }
    });

Actualy,我不知道如何在angular2中设置beforesend标头。我试过这个,但没有任何作用。它的给予 -

  

无法执行'打开' on' XMLHttpRequest':无效的网址"和
  响应状态:URL的500内部服务器错误:   http://111.118.241.110/B **** I / API / R ***** 1 /登录

我对post api的angular2代码 -

 import { Injectable } from '@angular/core';
    import { Http, Headers, Response, RequestOptions } from '@angular/http';
    import {Observable} from 'rxjs/Rx';
    import 'rxjs/add/operator/map'

    @Injectable()
    export class AuthenticationService {
        constructor(private http: Http) { }
        login(username: string, password: string) {
            var headers = new Headers();
            headers.append('Content-Type', 'application/x-www-form-urlencoded');
            headers.append('Authorization-ApiKey','Ak12mr27Xwg@d89ul');
            headers.append('Accept', 'application/json');            
            let options = new RequestOptions({ headers: headers });

            return this.http.post('http://111.118.241.110/B****i/api/R******1/Login', {
    UserName: username, Password: password } , options)
    .map((response: Response) => {

            let user = response;

         });

       }
    }

我非常确定,处理了API的所有CORS启用相关问题。可能是解决方案。 P.S:它对GET请求工作正常..

3 个答案:

答案 0 :(得分:1)

这对我有用,我希望它有所帮助......

saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            amountEntered = (EditText) findViewById(R.id.amountEntered);
            Integer bal = Integer.parseInt(custBal);
            Integer enteredAmount = Integer.parseInt(amountEntered.getText().toString());

            // check if amount entered is more than the balance:
            if( enteredAmount > bal ){

                final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MakePaymentActivity.this,R.style.MyAlertDialogStyle);
                alertDialog.setTitle("VERIFY AMOUNT");
                alertDialog.setMessage("Is entered amount correct?");
                alertDialog.setNegativeButton("NO",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
//Simply Exit here

                            }
                        });

            });

答案 1 :(得分:0)

最后的答案对我有用!但我用令牌来改进它:

.....
authenticate(token){
  console.log("user:" + token);
  var authdata = window.btoa(token+ ':');
  console.log("authdata:" + authdata);
  var header = new Headers();
  header.append('Authorization', 'Basic ' + authdata);
  header.append('contentType','application/json; charset=utf-8');
  header.append('Accept','application/json');
  header.append('Access-Control-Allow-Origin', '*');
  var option = new RequestOptions();
  option.headers = header;

  console.log(header);
    return this.http.get(this.baseUrl, option)
    .map((response:Response)=>response.json());
}

.....

答案 2 :(得分:0)

标题的使用在ANGULAR 6中已弃用。
使用HttpHeader:

import { HttpHeaders, HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {

      // Setting up the header
      this.header = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
      this.header = this.header.append('Accept', 'application/json');
      this.header = this.header.append('Authorization', yourAuthVariable);

}