如何在 Ionic 中使用 CORS 编写 Angular 2 服务?

2023-03-16前端开发问题
5

本文介绍了如何在 Ionic 中使用 CORS 编写 Angular 2 服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我无法使用 http 将我的 Angular 1 JavaScript 服务移动到 Angular 2 TypeScript 服务以发出 CORS 请求(这是使用 Ionic 版本 2).在 Angular 1 中,我做了这样的事情.

I'm having trouble moving my Angular 1 JavaScript service to a Angular 2 TypeScript service using http to make a CORS request (this is using Ionic version 2). In Angular 1, I do something like this.

angular.module('app.services',[])
.factory('LoginService', ['$http', function($http) { 
 var service = {};

 service.isUserLoggedIn = function() {
  var restUrl = 'http://10.10.10.25:8080/api/user/isloggedin';
  var options = {
   method: 'GET', url: restUrl, withCredentials: true,
   headers: { 
    'x-request-with': 'XMLHttpRequest', 
    'x-access-token': 'sometoken' 
   }
  };
  return $http(options);
 };

 return service;
}])

在使用 TypeScript 的 Angular 2 中,发生了很多变化(Promises/Observables).到目前为止,我的尝试如下所示.

In Angular 2 using TypeScript, a lot has changed (Promises/Observables). My attempt so far looks like the following.

import { Injectable } from '@angular/core';
import { Headers, Http, Response, RequestMethod, RequestOptionsArgs } from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class LoginService {
  constructor(private _http:Http) {

  }

  isLoggedIn():boolean {
    var r:any;
    var e:any;
    let url = 'http://10.10.10.25:8080/api/user/isloggedin';
    let options:RequestOptionsArgs = {
      url: url,
      method: RequestMethod.Get,
      search: null,
      headers: new Headers({
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'x-access-token' : 'sometoken'
      }),
      body: null
    };
    this._http.get(url, options).map(this.extractData).catch(this.handleError)
      .subscribe(
       response => { r = <any>response; console.log(r); }, 
       error => { e = <any>error; console.log(e); });
    return false;
  }

  private extractData(response:Response) {
    let body = response.json();
    return body.data || { };
  }

  private handleError(error:any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.log('error = ' + errMsg);
    return Observable.throw(errMsg);
  }
}

我不再确定如何在 Angular 2 中解决我在 Angular 1 中的问题

I am no longer sure how to address in Angular 2 what I had in Angular 1

  • withCredentials(请注意,https://angular.io/docs/js/latest/api/http/index/RequestOptionsArgs-interface.html#!#withCredentials-anchor 说 RequestOptionsArgs 应该有一个字段withCredentials 但我在 IDE Visual Studio 代码中收到一个错误,提示它在界面中不存在;ionic 可能使用的是较旧的 angular 2 版本?)
  • 标头(x-request-with 和 x-access-token)
  • 实际反应
  • withCredentials (note that https://angular.io/docs/js/latest/api/http/index/RequestOptionsArgs-interface.html#!#withCredentials-anchor says the RequestOptionsArgs should have a field withCredentials but I get an error in the IDE Visual Studio Code saying that it does not exists in the interface; ionic is probably using an older angular 2 version?)
  • headers (x-request-with and x-access-token)
  • the actual response

我做了更多的搜索,我能够理解如何插入标题并正确处理订阅.但是,withCredentials 仍然是个问题.

I did a little bit more searching, and I was able to understand how to insert headers and properly handle the subscription. However, the withCredentials is still a problem.

我发现这个 SO 帖子 angular2 xhrfields withcredentials true 并修改了我的构造函数,如下所示.现在可以了.

I found this SO post angular2 xhrfields withcredentials true and modified my constructor as follows. It works now.

constructor(@Inject(Http) private _http:Http) {
    let _build = (<any> _http)._backend._browserXHR.build;
    (<any> _http)._backend._browserXHR.build = () => {
      let _xhr = _build();
      _xhr.withCredentails = true;
      return _xhr;
    }
  }

推荐答案

withCredentails 的支持将出现在即将发布的 Angular2 RC2 版本中.它不是 RC1 版本的一部分...您需要稍等.

The support of withCredentails will be present in the RC2 version of Angular2 that will be released soon. It's not part of the RC1 version... You need to wait a bit.

使用 RC2,您将能够直接在请求选项中使用此属性:

With RC2, you will be able to use this property directly in the request options:

this.get('...', { withCredentials: true })

查看这个问题了解更多详情:

See this question for more details:

  • Angular 2 - http get withCredentials

这篇关于如何在 Ionic 中使用 CORS 编写 Angular 2 服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455

Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)...
2024-04-20 前端开发问题
5

CoffeeScript 总是以匿名函数返回
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)...
2024-04-20 前端开发问题
13