老师,请问为什么我请求数据会出现这种情况

来源:9-8 在不同的系统下测试图片上传的功能

Allwyes

2018-09-04

  1. 给谷歌浏览器设置跨域, 网络请求正常,

  2. 给项目设置跨域,网络请求也正常,

  3. 如果我不设置跨域或者不给浏览器设置跨域,网络请求就会报这个错

  4. http://img.mukewang.com/szimg/5b8e42fc00016eab18780174.jpg

  5. http://img.mukewang.com/szimg/5b8e431b00018cf015900282.jpg

  6. http://img.mukewang.com/szimg/5b8e43300001470b10020196.jpg

并且在真机上调试一网罗请求不成功,下面是我在模拟器上打印的日志

http://img.mukewang.com/szimg/5b8e43cd00016edc09120220.jpg


我试了很久也不知道问题出现在哪里,请老师帮我分析一下

写回答

4回答

Allwyes

提问者

2018-09-05

//img.mukewang.com/szimg/5b8f8e69000168af19280784.jpg



I am trying to set my proxyURL to my local server at http://myipaddress:3000 1 in the ionic.config.json however when i try to use the /api variable I get the error. "http://localhost:8080/api/auth/loginFailed to load resource: the server responded with a status of 405 (Method Not Allowed)". As you can see it is not using localhost:3000 as i hoped it would.

Does anyone know what is happening here/


设置了跨域,在浏览器上没问题,但是在真机上就和这个人遇到的问题差不多


0
0

Allwyes

提问者

2018-09-05

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

import { Injectable } from '@angular/core';

import 'rxjs/add/operator/toPromise';



// import { Observable } from '../../../node_modules/rxjs/Observable';

// import { Observable } from 'rxjs/Rx';

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

// import 'rxjs/add/operator/map'

// import 'rxjs/add/operator/catch'


/*

 Generated class for the RestProvider provider.


 See https://angular.io/guide/dependency-injection for more info on providers

 and Angular DI.

*/

@Injectable()

export class RestProvider {

 public baseurl = 'https://imoocqa.gugujiankong.com/api'

 constructor(public http: HttpClient) {

   console.log('Hello RestProvider Provider');

 }


 

 // private getUrlReturn(url: string): Observable<string[]> {

 //   return this.http.get(url).map(this.extractData).catch(this.handleError)

 // }

 // private extractData(res: Response) {

 //   let body = res.json();

 //   return JSON.parse(body) || {}

 // }

 // private handleError(error: Response | any) {

 //   let errMes: string;

 //   if (error instanceof Response) {

 //     const body = error.json() || '';

 //     const err = body.error || JSON.stringify(body);

 //     errMes = `${error.status} - ${error.statusText || ''} ${err}`


 //   } else {

 //     errMes = error.message ? error.message : error.toString()

 //   }

 //   return Observable.throw(errMes)

 // }


   // 此处使用的post模式为非严格模式,如果要使用严格模式,请把参数放在第二个位置 覆盖null

   public post(url: string, params: any = null, otherOptions?:any): any {

     // 此处使用的post模式为非严格模式,如果要使用严格模式,请把参数放在第二个位置 覆盖null

     return this.send(url,params,{},'POST')

   }

   public put(url: string, params: any = {}, otherOptions?:any): any {

     // 此处使用的post模式为非严格模式,如果要使用严格模式,请把参数放在第二个位置 覆盖null

     return this.send(url,params,{},'PUT')

   }

   // get数据

   public get(url: string, params?: any,otherOptions:any={}): any {

   

     // let request = new HttpRequest('GET',url,{});

     return this.send(url,params,otherOptions,'GET')

     // return this.http.get(url, params);

   }

   public query(url: string, params?: any): any {

   

     // let request = new HttpRequest('GET',url,{});

     return this.send(url,params,{},'GET')

     // return this.http.get(url, params);

   }

   // 删除相关请求

   public delete(url: string, params?: any): any {

     return this.http.delete(url, params);

   }


   private send(url, data, otherOptions:any={}, method = 'GET'){

     url =  this.baseurl + url

     let request:any;

     let others:any;

     if(otherOptions){

       let option = String(otherOptions.token)

       let headers :HttpHeaders= new HttpHeaders({

         "Content-Type": 'application/json;charset=utf-8',

         "Accept": 'text/html,application/json,application/xml;q=0.9,image/webp,*/*;q=0.8',

         "Accept-Language": 'zh-CN',

         "refreshToken": '',

         'x-auth-token':option

       });

       others = {headers:headers}

    }

     if(method == 'GET'){

       let params =  this.encodeHttpParams(data)

       console.log(11111)

       request = new HttpRequest(method,url,{params:params,...others});

     }else if (method == 'POST'||"PUT"){

       request = new HttpRequest(method,url,data,others);

     }else if(method == 'DELETE'){


     }    

     return  new Promise((resolve,reject)=>{

       return this.http.request(request).toPromise().then((res)=>{

           return resolve(res)

       }).catch((err:HttpErrorResponse)=>{

         reject(err)

       })

     })

     // return this.http.request(request).toPromise()

     

 

   }

   private encodeHttpParams(params: any): any {

     if (!params) return null;

     return new HttpParams({fromObject: params});

   }


 private responseSuccess(res: any, callback) {

   if (res.code !== '0') { // 失败

     if (res.msg) {

       callback({code: res.code, msg: res.msg});

     } else {

       const data = res.data;

       let errorMsg = '操作失败!';

       data.map(i => {

         errorMsg = i.errorMsg + '\n';

       });

       callback({code: res.code, msg: errorMsg});

     }

   } else {

     callback(res);

   }

 }


 private requestFailed(url: string, err) {

   let msg = '请求发生异常';

   const status = err.status;

   if (status === 0) {

     msg = '请求失败,请求响应出错';

   } else if (status === 404) {

     msg = '请求失败,未找到请求地址';

   } else if (status === 500) {

     msg = '请求失败,服务器出错,请稍后再试';

   } else {

     msg = '未知错误,请检查网络';

   }

   return msg;

 }

 // public getList(){

 //   return this.get('/pc/client/enquiryGoods/index',{})

 // }

 


}


----------------------------------这是调用------------------------------


async checkLogin() {

 var loading =  super.showLoading(this.loadingCtrl,'请稍候')

   try {

     const res =  await this.storage.get('UserId')

     this.logined = res ? true : false

     const {body} = await this.api.getUserInfo({userid:res})

     loading.dismiss()

     var users  = JSON.parse(body)

     console.log(users)

     this.userInfo = users


   } catch (error) {

     loading.dismiss()

     this.showToast(this.toastCtrl,error)

     console.log(error)

   }



 }





0
1
Allwyes
请求数据的api的代码我贴到上面了
2018-09-05
共1条回复

Parry

2018-09-05

后台我一直没有变动过。
怎么会有 options 的请求?
你贴下你的代码我看看。


0
2
Parry
回复
Allwyes
那就奇怪了,我看你那个错误截图也看不出具体的错误原因,你修改成我的试试呢?
2018-09-08
共2条回复

Allwyes

提问者

2018-09-04

网络请求的报错信息,我给打印出来了

//img.mukewang.com/szimg/5b8e48430001808317160344.jpg

0
0

快速上手Ionic3多平台开发企业级问答社区

新手可学,独立开发跨iOS/Android/微信平台项目

613 学习 · 750 问题

查看课程