【问题标题】:Angular - Every request is being blocked by CORSAngular - 每个请求都被 CORS 阻止
【发布时间】:2021-12-26 21:52:23
【问题描述】:

我正在为我的大学制作一个带有 java 后端的 angular 12 应用程序。 我正在测试 Angular 的 http 客户端,但我无法发出任何请求,因为它被 CORS 阻止了。 首先,我尝试向我的后端服务器发出 POST 请求,但没有成功。 角度代码:

const API_URL = 'http://localhost:9080'

@Injectable({
  providedIn: 'root'
})

export class AuthService {

  constructor(private http:HttpClient, private router:Router) { }

  login(user:User) { 
    this.http.post(`${API_URL}/login`, user, {observe:'response'}).subscribe(result => { 
      console.log(result)
    })
  }

The response was this.

所以,我搜索了一下,发现这个大部分是服务器端的,虽然我可以在 Insomnia/Postman 中正常发出请求,但我还是尝试在我的 server.xml 上配置 cors。

但后来我有了尝试使用外部 API 的想法。 我尝试向 Google 发出 GET 请求,结果却得到了回复:

Response from google

每个外部 API 都会发生这种情况,所以我不认为问题出在服务器端,而是 Angular,但我找不到任何不会说问题出在服务器端的解决方案,但不可能,因为我不能向任何网站提出任何请求,对吧?

【问题讨论】:

    标签: angular api cors integration


    【解决方案1】:

    虽然您的后端和前端似乎在同一个来源,但实际上并非如此

    这些来源不同,因为它们使用不同的端口:
    http://example.com:80
    http://example.com:8080

    如果协议、端口(如果指定)和主机相同,则两个 URL 具有相同的来源。

    修复 CORS 总是在服务器端完成。基本上,出于安全原因,浏览器不允许您从与前端托管位置不同的位置的脚本发出请求。 Read in detail here

    对于开发,您可以禁用浏览器 CORS 检查。您可以下载浏览器扩展程序或使用 chrome 标志。 Read here about the flags

    "--user-data-dir=/tmp/chrome-sesh", "--disable-web-security"
    

    【讨论】:

    • 我明白了,谢谢!如果我将此应用程序部署到生产服务器(我们正在考虑 heroku),这意味着如果服务器(例如 google)具有正确的标头,这将自动修复,对吗?
    • 如果配置正确,是的。 developer.mozilla.org/en-US/docs/Web/Security/…。不要使用会破坏 CORS(XSS 预防)目的的通配符
    猜你喜欢
    • 2018-10-18
    • 2022-01-24
    • 2018-09-12
    • 2021-10-25
    • 2020-08-16
    • 2022-11-01
    • 2020-07-18
    • 2022-01-14
    • 2020-08-16
    相关资源
    最近更新 更多