【问题标题】:How to resolve api url issue in angular 6如何解决 Angular 6 中的 api url 问题
【发布时间】:2019-09-19 04:21:07
【问题描述】:

我正在尝试在本地运行此应用程序但无法正常工作。我尝试了很多次但我找不到问题。我认为 api url 问题。如果我运行此应用程序,我会遇到错误。如何解决这个问题?我怎样才能不出错地运行这个应用程序?

zone.js:2935 GET http://salembrothers.ca/app/api/getSettings/social 404 (Not Found)  
products:1 Access to XMLHttpRequest at 'http://salembrothers.ca/app/api/getSettings/social' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

完整代码:https://github.com/MarouaneSH/Angular-6-Shopping-cart-with-Laravel

api.service.ts:

import { HttpClient , HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError } from 'rxjs/operators/catchError';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { Observable } from 'rxjs/Rx'


const apiUrl =  "http://salembrothers.ca/app/api";

@Injectable()
export class ApiService {


  constructor(private http:HttpClient) { }

  get(path,params:HttpParams = new HttpParams()){
      return this.http.get(`${apiUrl}/${path}`, {params})
             .pipe(
               catchError(this.handleError)
            );
  }


 post(path,params){
      return this.http.post(`${apiUrl}/${path}`, params)
                .pipe(
                  catchError(this.handleError)
                );
 }

  handleError(err:any){
    return Observable.throw(err);
  }
}

【问题讨论】:

    标签: angular6 angular5 angular7


    【解决方案1】:

    由于错误消息显示“已被 CORS 策略阻止”,您需要在 API 服务器中启用 CORS,您的 API 服务器/框架可能还需要将运行 Angular 的“http://localhost:4200”列入白名单。

    【讨论】:

    • 我也面临同样的问题。我正在从我的 xampp 本地主机服务器运行
    • 如何开启api服务器?
    猜你喜欢
    • 2019-03-14
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2015-10-02
    • 2014-08-09
    • 2019-03-19
    • 1970-01-01
    相关资源
    最近更新 更多