【发布时间】:2021-04-08 17:04:51
【问题描述】:
我创建了一个简单的应用程序,其中包含第三方电子邮件发送 api 实现,以通过联系表单获取电子邮件。当我在本地主机或 github 页面上运行应用程序时,我收到此错误:
Access to XMLHttpRequest at 'https://api.mailjet.com/v3.1/send' from origin 'https://myrepo.github.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
该问题的解决方案是什么。显然我不能在 API 端应用任何解决方案,我所要做的就是从我的角度代码。 这是我在 http post 请求中实现的内容
sendMail(): Observable<any>{
let API_URL='https://api.mailjet.com/v3.1/send';
let data={
"Messages":[
{
"From": {
"Email": "myemail@gmail.com",
"Name": "My Name"
},
"To": [
{
"Email": "myemail@gmail.com",
"Name": "My Name"
}
],
"Subject": "My first Mailjet email",
"TextPart": "Greetings from Mailjet.",
"HTMLPart": "<h3>Dear passenger 1, welcome to <a href=https://www.mailjet.com/>Mailjet</a>!</h3><br />May the delivery force be with you!",
"CustomID": "AppGettingStartedTest"
}
]
};
console.log('sending email....')
console.log(data);
this.httpClient.post<any>(API_URL,data,{
headers: new HttpHeaders({
'Content-Type':'application/json',
'Authorization':'Basic VGIzOTIsasdasdasdasdasdrewetwfdsfasdasMjI0NWUVcDFGA='
})
}).subscribe(res=>{
console.log(res);
},err=>{
console.log(err);
});
return null;//ignoring this for now.
}
【问题讨论】:
-
我想这是 CORS 的全部意义,你不能只在客户端工作。
-
我知道我可以通过使用 cors disable 选项运行 chrome 来绕过这个问题。但这不是最终的解决方案。另外,mailjet 提供了一个功能 API,所以我不能说他们的 API 不起作用。他们的 API 也由 postman 工作。