Javascript 如何在Ionic 2中通过POST请求发送数据

Javascript 如何在Ionic 2中通过POST请求发送数据,javascript,api,ionic2,google-fusion-tables,http-status-code-401,Javascript,Api,Ionic2,Google Fusion Tables,Http Status Code 401,我已经使用googleapi创建了一个应用程序,我正在使用googlefusion tables作为后端,因此我也启用了fusion table API。我正在使用爱奥尼亚2制作一款混合应用程序GET非常适用于阅读表格和POST给定的 错误401 功能提交器(按钮){ var accessToken=document.getElementById(“accessToken”).value; 变量查询=”https://www.googleapis.com/fusiontables/v2/qu

我已经使用
googleapi
创建了一个应用程序,我正在使用
googlefusion tables
作为后端,因此我也启用了
fusion table API
。我正在使用爱奥尼亚2制作一款混合应用程序
GET
非常适用于阅读表格和
POST
给定的
错误401

功能提交器(按钮){
var accessToken=document.getElementById(“accessToken”).value;
变量查询=”https://www.googleapis.com/fusiontables/v2/query?sql=INSERT 进入“+answerTableId+”(答案、问题ID、用户ID)值(“+button.value+”、“+currentQueNo+”、“+UserID+”)“+key+”&access_-token=“+accessToken;
var xhttp2=新的XMLHttpRequest();
xhttp2.onreadystatechange=函数(){
//警报(this.readyState+“”+this.status);
if(this.readyState==4){
警报(this.responseText);
}
};
xhttp2.open(“POST”,查询,true);
xhttp2.setRequestHeader('Authorization',accessToken);
xhttp2.send();

}
也许您只是忘记了授权值中的“持有人”:

xhr.setRequestHeader('Authorization', 'Bearer ' + oauthToken.access_token);
或者,您可能只是在查询中对accessToken进行了错误编码(您需要使用encodeURIComponent(accessToken))

如果这是从浏览器而不是从NodeJS调用的,您可能会被CORS问题阻止


另外,与您的问题无关:您创建请求的方式对于SQL注入非常合理。一些随机用户可能会在不知道任何密码的情况下删除整个数据库。

Sincw您使用的是ionic 2,而不是像下面的代码示例那样创建一个扩展主角度
http
的拦截器,应该为您提供所有技巧,我建议您遵守它。因为它是离子2角2+

首先,创建一个类来扩展http类,如so
api handler.ts

import { Storage } from '@ionic/storage';
import { environment } from './environment';
import { Injectable } from '@angular/core';
import { Headers, Http, ConnectionBackend, RequestOptions, RequestMethod, RequestOptionsArgs } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from "rxjs/Observable";

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/finally';
import 'rxjs/add/observable/throw';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/mergeMap';

/*
  Generated class for the ApiHandler provider.

  this is used to make communication with our endpoint where we pass endpoint 
  header information and any form of manipulation
*/
@Injectable()
export class ApiHandler extends Http {
  private bearer: string = 'Plutus';

  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _storage: Storage) {
    super(backend, defaultOptions);
  }

  /**
    * This is used to call our api service by inputing the service url
    * @param service_url 
    * @param method  
    * @param params 
    * @param options 
    * 
    * @return Observable<any>
    */
  callService(service_url: string, method: RequestMethod, params?: any, options?: RequestOptionsArgs): Observable<any> {

    if (params == null) {
      params = {};
    }

    options = this.requestOptions(method, params, options);


    let token_promise: Promise<any> = this._storage.get('token');

    return Observable.fromPromise(token_promise)
      .mergeMap(token => {
        console.log("token from storage", token);
        if (options.headers == null && token != null) {
          options.headers = new Headers({
            'Authorization': `${this.bearer} ${token}`
          });
        }

        return super.request(this.getFullUrl(service_url), options)
          .catch(this.onCatch);
      });
  }


  /**
   * Request options is used to manipulate and handle needed information before
   * it is sent to server
   * @param options
   * @returns {RequestOptionsArgs}
   */
  private requestOptions(method: RequestMethod, params: any, options?: RequestOptionsArgs): RequestOptionsArgs {
    if (options == null) {
      options = new RequestOptions();
    }
    options.method = method;

    if (options.method === RequestMethod.Post || options.method === RequestMethod.Put) {
      options.body = params;
    } else {
      options.params = params;
    }

    return options;
  }

  /**
   * Build API url.
   * and we remove any leading / from the service calls since 
   * we are not needing then in making request calls
   * e.g localhost:1337//base... to localhost:1337/base..
   * @param url
   * @returns {string}
   */
  private getFullUrl(url: string): string {
    if (url.charAt(0) == "/") {
      url = url.substring(1);
    }
    return environment.endpoint + url;
  }


  /**
     * Error handler.
     * @param error
     * @param caught
     * @returns {ErrorObservable}
     */
  private onCatch(error: any, caught: Observable<any>): Observable<any> {
    return Observable.throw(x);
  }

}
最后,要在您的案例中使用它,只需将其添加到构造函数中,然后像这样直接使用它

import { IFeedBack } from './../interfaces/ifeedback';
import { Observable } from 'rxjs/Observable';
import { ApiHandler } from './../util/api-handler';
import { Injectable } from '@angular/core';
import { RequestMethod } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the FeedBackServiceProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class FeedBackService {

  constructor(private _apiHandler: ApiHandler) {
  }

  /**
   * this is used to create new feedback 
   * @param feedback 
   */
  create(feedback: IFeedBack): Observable<IFeedBack> {
    return this._apiHandler.callService('/feedback', RequestMethod.Post, feedback)
      .map(res => <IFeedBack>res.json());
  }

}
从“/../interfaces/IFeedBack”导入{IFeedBack};
从“rxjs/Observable”导入{Observable};
从“/../util/api处理程序”导入{ApiHandler};
从“@angular/core”导入{Injectable};
从'@angular/http'导入{RequestMethod};
导入'rxjs/add/operator/map';
/*
为FeedBackServiceProvider提供程序生成的类。
看见https://angular.io/docs/ts/latest/guide/dependency-injection.html
有关提供者和Angular 2 DI的更多信息。
*/
@可注射()
导出类反馈服务{
构造函数(private\u apiHandler:apiHandler){
}
/**
*这用于创建新的反馈
*@param反馈
*/
创建(反馈:IFeedBack):可观察{
返回此。_apidhandler.callService('/feedback',RequestMethod.Post,feedback)
.map(res=>res.json());
}
}
然后,您可以使用新参数调用create来发送,然后订阅它

我想这应该对你有好处。

非常感谢,我猜是“送信人”少了一部分,帮了我的忙。此外,我在使用API密钥时丢失了一封信。
import { IFeedBack } from './../interfaces/ifeedback';
import { Observable } from 'rxjs/Observable';
import { ApiHandler } from './../util/api-handler';
import { Injectable } from '@angular/core';
import { RequestMethod } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the FeedBackServiceProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class FeedBackService {

  constructor(private _apiHandler: ApiHandler) {
  }

  /**
   * this is used to create new feedback 
   * @param feedback 
   */
  create(feedback: IFeedBack): Observable<IFeedBack> {
    return this._apiHandler.callService('/feedback', RequestMethod.Post, feedback)
      .map(res => <IFeedBack>res.json());
  }

}