Angular的POST请求变成了OPTIONS请求,无法更改后端以解决CORS问题。
创始人
2024-10-24 09:01:43
0

要解决Angular中POST请求变成OPTIONS请求的CORS问题,可以尝试使用代理服务器来转发请求。以下是一个示例代码:

  1. 首先,创建一个proxy.conf.json文件来配置代理服务器,内容如下:
{
  "/api": {
    "target": "http://backend-api-url",
    "secure": false,
    "changeOrigin": true,
    "pathRewrite": {
      "^/api": ""
    }
  }
}
  1. angular.json文件中的architect部分添加以下内容:
"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "your-app:build",
    "proxyConfig": "proxy.conf.json"
  },
  "configurations": {
    "production": {
      "browserTarget": "your-app:build:production"
    }
  }
},
  1. 在你的Angular服务中,使用代理服务器的URL来发送POST请求。例如:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class YourService {
  private apiUrl = '/api';

  constructor(private http: HttpClient) { }

  postData(data: any) {
    return this.http.post(`${this.apiUrl}/your-endpoint`, data);
  }
}

请确保将your-app替换为你的应用程序名称,并将http://backend-api-url替换为你的后端API的URL。

使用代理服务器转发请求时,Angular应用程序将向代理服务器发送请求,然后代理服务器将请求转发到后端API。这样可以避免浏览器发送OPTIONS请求,解决CORS问题。

相关内容

热门资讯

透视黑科技"wepo... 《透视黑科技"wepoker开脚本视频"详细辅助透明教程(私局代打技巧)》 wepoker开脚本视频...
透视美元局"hhpo... 透视美元局"hhpoker到底可以作弊码"详细辅助大神讲解(黑侠破解辅助);建议优先通过hhpoke...
透视总结"wepok... 透视总结"wepoker怎么设置房间"详细辅助玩家教你(万能挂透视);1.wepoker怎么设置房间...
透视苹果版"poke... 透视苹果版"pokemmo辅助官网"详细辅助德州论坛(内置辅助透视)1、不需要AI权限,帮助你快速的...
透视透视"wepok... 1、透视透视"wepoker有没有挂"详细辅助微扑克教程(插件下载透视);详细教程。2、wepoke...
透视工具"wepok... 1、透视工具"wepoker养号规律"详细辅助解密教程(购买模拟器攻略)(UU poker、wepo...
透视新版"菠萝辅助器... 透视新版"菠萝辅助器免费版的功能介绍"详细辅助玩家教你(是有挂软件教程);科技安装教程;136704...
辅助透视"wejok... 辅助透视"wejoker辅助软件视频"详细辅助2025教程(辅助脚本教程)是由北京得wejoker辅...
辅助透视"来玩app... 1、辅助透视"来玩app破解"详细辅助力荐教程(辅助器下载透明)。2、来玩app破解透视辅助简单,来...
透视有挂"we po... 自定义we poker辅助器v3.3系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专...