我有一个用户填写的联系人表单,它会被发布到我的Web中,使用nodemailer
发送。
CORS在本地运行客户端和API时与预期的一样工作:
客户端
本地主机:4200带有POST请求
sendEmail(queryObject: any) {
const body = JSON.stringify(queryObject);
const headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/api/sendemail', body, {headers: headers})
.map((response: Response) => response.json());
}
API
本地主机:3000
但是,当我将API部署到heroku并将客户机中的POST URL更改为指向Heroku时,就会得到飞行前错误:
选项https://keilcarpenter-portfolioapi.herokuapp.com/api/sendemail 503 (服务不可用) XMLHttpRequest无法加载https://keilcarpenter-portfolioapi.herokuapp.com/api/sendemail。对飞行前请求的响应不会通过访问控制检查:请求的资源上没有“访问-控制-允许-原产地”标题。因此,“http://localhost:4200”源是不允许访问的。响应具有HTTP状态代码503。
我确信在我的API上已经在server.js中正确地设置了CORS:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
为什么CORS在当地接受这个职位,而在Heroku不接受?
发布于 2019-09-17 04:32:41
好的,当您从不同的端口部署webapp或应用程序时,您将需要处理CORS
,因此您需要配置服务器,使其更加友好,并接受CORS
(使您能够接收来自不同来源的请求)。在tomcat修改web.xml,防火墙做另一件事,在天蓝色等.每个服务都有自己的配置。但是在angular
中,您必须配置一个代理来绕过这些端口问题。所以创建一个像这样的proxy.conf.json
{
"/angular": {
"target": {
"host": "github.com",
"protocol": "https:",
"port": 443
},
"secure": false,
"changeOrigin": true,
"logLevel": "info"
}
}
然后在package.json
中创建这样的脚本
"scripts": {
"start": "ng serve --proxy-config proxy.conf.json",
然后运行ng serve
、运行ng start
或npm start
关于这件事的很好的文档:
https://github.com/angular/angular-cli/pull/1896/commits/a81aa3b6117848a1c9c99d3b6d0666433b5144e0
https://stackoverflow.com/questions/43038936
复制