【问题标题】:Cross origin error between angular cli and flask角度cli和烧瓶之间的交叉原点错误
【发布时间】:2020-02-20 10:57:14
【问题描述】:

首先我将用户 ID 和密码从 UI(角度)发布到烧瓶

  public send_login(user){
           console.log(user)
           return 
     this.http.post(this.apiURL+'/login',JSON.stringify(user),this.httpOptions)
    .pipe(retry(1),catchError(this. 
     handleError))
     } 

接下来我从后端收到它

backend error

所有操作都正常运行,但在控制台上出现跨源错误

Error at UI console

下面会提到Ui端的http选项

constructor(private http: HttpClient) { }
  // Http Options
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': 'http://localhost:9000',
      'Access-Control-Allow-Methods': "GET,POST,OPTIONS,DELETE,PUT",
      'X-Requested-With': 'XMLHttpRequest',
      'MyClientCert': '',        // This is empty
      'MyToken': '' 
    })
  }

在后端声明的 cors 在下面提到

cors = CORS(app, resources={r"/login": {"origins": "*"}})
 @app.route('/login', methods=['GET','POST'])
 def loginForm():
 json_data = ast.literal_eval(request.data.decode('utf-8'))
  print('\n\n\n',json_data,'\n\n\n')

我找不到是问题正在引发

注意:跨域在登录过程中出现,否则在连续步骤中

【问题讨论】:

  • 可以在@app.route('/login', methods=['GET','POST']) 中添加OPTIONS 吗?
  • 哪个端口是角度运行,哪个是闪存运行。您是否设置了代理配置?这里有关于如何设置代理的说明:angular.io/guide/build

标签: python-3.x angular typescript flask angular-ui-router


【解决方案1】:

在您的 app.py 中添加以下代码

CORS(app, supports_credentials=True)

从前端使用

{with-credentials :true}

它将启用前端和后端之间的通信

【讨论】:

    【解决方案2】:

    对我来说,调用似乎并没有离开前端(至少在我的经验中是这样的),因为浏览器正在保护它。

    在项目的src/ 文件夹中创建一个新文件proxy.conf.json

    {
      "/backendApiUrl": {      <--- This needs to reflect the server backend base path
        "target": "http://localhost:9000",    <-- this is the backend server name and port
        "secure": false,
        "logLevel": "debug"    <--- optional, this will give some debug output
      }
    }
    

    在文件angular.json(CLI 配置文件)中,将以下proxyConfig 选项添加到服务目标:

    "projectname": {
      "serve": {
        "builder": "@angular-devkit/build-angular:dev-server",
        "options": {
          "browserTarget": "your-application-name:build",
          "proxyConfig": "src/proxy.conf.json"      <--- this is the important addition
        },
    

    只需调用ng serve 即可使用此代理配置运行开发服务器。

    您可以阅读https://angular.io/guide/build中的Proxying to a backend server部分

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 2015-04-30
      • 1970-01-01
      相关资源
      最近更新 更多