Access-Control-Allow-Origin无法与ionic 5应用程序一起使用 [英] Access-Control-Allow-Origin not working with ionic 5 app

查看:119
本文介绍了Access-Control-Allow-Origin无法与ionic 5应用程序一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照教程在Ionic应用程序中从服务器发送和接收数据,但是由于CORS,我在这样做时遇到了麻烦。我对CORS问题非常熟悉,并使用了 Access-Control-Allow-Origin将我的Javascript Ajax代码连接到服务器上的PHP后端时,通常会找到解决方案。但是,似乎对Ionic无效。
我已经在SO上看到了一些问题/答案,并且阅读了一些博客,他们都说这应该可以,但是没有用。


我已经完成了控制我的端点并在其中创建了一个PHP文件,如下所示:

  header( Access-Control-Allow-Origin:* ;); 
$ strStudents ='{
学生:[
{
id:1,
name: Enola Rowe,
class: tony@mcu.com,
address: 131 Oswaldo Street;
},{
id:2,
name: Timmothy Lueilwitz,
age: 15,
地址: 37137 Abbigail Lock;
},{
id:3,
name: Madilyn Pacocha,
age: 14,
地址: 094 Morris Plains;
},{
id:4,
name: Harley Cremin,
age: 17,
地址: 14855凯茜广场;
},{
id:5,
name: Juana Ziemann,
age: 16,
地址: 612 Dayana Stream;
}
]
}’;
返回$ strStudents;
?>

我还尝试了其他组合,例如:

  header('Access-Control-Allow-Origin:*'); 
标头( Access-Control-Allow-Headers:Origin,X-Requested-With,Content-Type,Accept);

但没有雪茄。 Ionic中的相关代码(可能不相关,但我还是把它放在这里)如下:

 出口类ApiService {
base_path ='http://mywebsite.com/App';

构造函数(私有http:HttpClient){}

// Http Options
httpOptions = {
标头:new HttpHeaders({
'Content-Type':'application / json'
})
}

handleError(error:HttpErrorResponse){
if(Error.error instanceof ErrorEvent){
//发生客户端或网络错误。相应地处理它。
console.error(’发生错误:’,error.error.message);
;
} else {
//后端返回的响应代码失败。
//响应主体可能包含有关出了什么问题的线索,
console.error(
`后端返回的代码$ {error.status},+正文为:$ {error .error}`);
}
//返回可观察到并带有面向用户的错误消息
return throwError(
‘发生了什么坏事;请稍后再试。’);
}

//创建新项目
createItem(item):Observable< Student> {
返回this.http.post< Student>(this.base_path,JSON.stringify(item),this.httpOptions)
.pipe(retry(2),catchError(this.handleError)));
}

//通过ID获取学生的数据
getItem(id):Observable< Student> {
返回this.http.get< Student>(this.base_path +‘/’+ id,this.httpOptions)
.pipe(retry(2),catchError(this.handleError)));
}

//获取学生列表
getList():Observable< Student> {
返回this.http.get< Student>(this.base_path)
.pipe(retry(2),catchError(this.handleError)));
}

我得到的错误是:


跨域请求被阻止:同一来源策略不允许读取
http:/上的远程资源/mywebsite.com/App 。 (原因:CORS标头
'Access-Control-Allow-Origin'缺失)


(多次)及以后:


后端返回代码0,正文为:[object ProgressEvent]
api.service.ts:31:14错误发生了一些不好的事情;请稍后再试


我在做什么错了?


我也想请注意,我已经在此处中描述了代理方法,但是不得已而为之,因为它给我增加了在服务器上添加新文件和更改路径的灵活性。


编辑:由于有些评论说没有完成足够的研究,因此我列出了一些我尝试过的来源中:


https://www.joshmorony.com/dealing-with-cors-cross-origin-resource-sharing-in-ionic-applications/ (由此开始)


https://www.techiediaries.com/ ionic-2-proxy / (此操作无效-应用无法识别代理)


https://ionicframework.com/blog/handling-cors-issues-in-ionic/ (没有ionic.project文件-也尝试了projectname.project文件和其他组合)


https://github.com/ionic-team/ionic-framework/issues/16233 (与此问题相关的公开错误报告)


在离子型中被CORS政策阻止-5 angular (不用说也没有用)


我也尝试过 Ionic的本地Http ,但出现了相同的错误。


我已经在Firefox和Chrome浏览器中尝试过此


我认为人们认为这是一个简单的php编码错误。我相信它与Ionic和HttpClient息息相关。

解决方案

我找到了问题和解决方法。正如预期的那样,它在Ionic App的代码中。但这不是我所期望的。希望这对处于同样困境的人可能有用。问题是这一行:

  base_path =‘http://mywebsite.com/App’; 

这应该是:

  base_path ='http://mywebsite.com/App/'; 

细微差别,但很重要。仔细查看控制台日志后,我发现它给出了301错误,事实证明这是永久重定向。在这种情况下,重定向到第二个URI(带有斜杠)。如果我一直使用 base_path ='http://mywebsite.com/App/index.php'; 或任何其他文件名,我可能不会看到此错误。 / p>

301重定向当然返回 Content-Type:text / html,因为它是纯文本页面,而应用程序期望 Content-Type:application / json从而导致CORS错误。


I am following a tutorial to send and receive data from my server in an Ionic application and I am having trouble doing that because of CORS. I am very familiar with the CORS issue and have used the "Access-Control-Allow-Origin" solution often when connecting my Javascript Ajax code to the PHP backend on my server. However, nothing seems to work for Ionic. I've seen several questions/answers here on SO, as well as read some blogs, and they all say this should work but it doesn't.

I have complete control over my endpoint and have created a PHP file there that looks like this:

header("Access-Control-Allow-Origin: *");
$strStudents = '{
  "students": [
  {
    "id": 1,
    "name": "Enola Rowe",
    "class": "tony@mcu.com",
    "address": "131 Oswaldo Street"
  },{
    "id": 2,
    "name": "Timmothy Lueilwitz",
    "age": "15",
    "address": "37137 Abbigail Lock"
  },{
    "id": 3,
    "name": "Madilyn Pacocha",
    "age": "14",
    "address": "094 Morris Plains"
  },{
    "id": 4,
    "name": "Harley Cremin",
    "age": "17",
    "address": "14855 Cathy Square"
  },{
    "id": 5,
    "name": "Juana Ziemann",
    "age": "16",
    "address": "612 Dayana Stream"
  }
  ]
}';
return $strStudents;
?>

I have also tried other combinations such as:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

but no cigar. The relevant code in Ionic (probably not relevant but I'll put it here anyway) looks like this:

  export class ApiService {
  base_path = 'http://mywebsite.com/App';
  
  constructor(private http: HttpClient) { }

  // Http Options
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }

  handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
       // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occured: ', error.error.message);
      ;
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` + `Body was: ${error.error} `);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }

  // Create a new item
  createItem(item): Observable<Student> {
    return this.http.post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
    .pipe(retry(2), catchError(this.handleError));
  }

  // Get a Student's data by ID
  getItem(id): Observable<Student> {
    return this.http.get<Student>(this.base_path + '/' + id, this.httpOptions)
    .pipe(retry(2), catchError(this.handleError));
  }

  // Get a list of Students
  getList(): Observable<Student> {
    return this.http.get<Student>(this.base_path)
    .pipe(retry(2), catchError(this.handleError));
  }

The errors I am getting are:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://mywebsite.com/App. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

(multiple times) and later:

Backend returned code 0, Body was: [object ProgressEvent] api.service.ts:31:14 ERROR Something bad happened; please try again later.

What am I doing wrong?

Also, I want to note that I have studied the proxy method described here but that would be a last resort since it gives me less flexibility to add new files and change paths on my server.

Edit: Since some comments say not enough research has been done, I am listing a few of the sources I have tried:

https://www.joshmorony.com/dealing-with-cors-cross-origin-resource-sharing-in-ionic-applications/ (started with this)

https://www.techiediaries.com/ionic-2-proxy/ (this did not work - the app does not recognize the proxy)

https://ionicframework.com/blog/handling-cors-issues-in-ionic/ (there is no ionic.project file - also tried the projectname.project file and other combinations)

https://github.com/ionic-team/ionic-framework/issues/16233 (An open bug report related to this issue)

blocked by CORS policy in ionic-5 angular (needless to say that didn't work also)

I have also tried the Native Http in Ionic, but got the same error.

I have tried this in Firefox as well as Chrome

I think people are assuming this is a simple php coding error. I believe it has more to do with Ionic and the HttpClient.

解决方案

I found the problem and the fix. As expected it was in the Ionic App's code. But it was not quite what I expected. Hopefully, this may be useful to someone in the same predicament. The problem was this line:

base_path = 'http://mywebsite.com/App';

This was supposed to be:

base_path = 'http://mywebsite.com/App/';

Subtle difference but important. After looking carefully at the console logs, I discovered that it was giving a 301 error, which turns out to be a "Permanent Redirect". The redirect in this case was to the second URI (with the slash attached). Had I been using base_path = 'http://mywebsite.com/App/index.php'; or any other file name I probably would not have seen this error.

The 301 redirect was, of course, returning "Content-Type: text/html" since it was a plain text page whereas the app was expecting "Content-Type: application/json" and hence the CORS error.

这篇关于Access-Control-Allow-Origin无法与ionic 5应用程序一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆