繁体   English   中英

角度cli和烧瓶之间的交叉原点错误

[英]Cross origin error between angular cli and flask

首先,我将用户 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))
     } 

接下来我从后端收到它

后端错误

所有操作都正常工作,但在控制台上出现了交叉原点错误

UI 控制台出错

下面提到了 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.py 中添加以下代码

CORS(app, supports_credentials=True)

并从前端使用

{with-credentials :true}

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

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

在项目的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部分

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM