我有一个nodejs express api部署在AWS EB上,而我的angular应用部署在AWS S3上
我像这样设置服务器端res头
var corsOptions={
origin:true,
methods:['GET','POST','PUT','DELETE','OPTIONS'],
optionsSuccessStatus:200,
credentials:true,
};
app.use(cors(corsOptions));
我的httpclient如下所示
postRequest(url: string, body: string): Observable<string> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
withCredentials: true
};
return this.httpClient.post<string>(API_URL + url, body, httpOptions)
.pipe(
tap(
res => {
console.log('public.service postRequest get res: ' + JSON.stringify(res));
},
err => console.log('public.service postRequest get err: ' + JSON.stringify(err)),
() => console.log('public.service postRequest completed')
)
);
}
当我发出post请求时,我的请求头如下所示
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6,ja;q=0.5
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: node-express-env.eba-aqztwrxw.ap-east-1.elasticbeanstalk.com
Origin: http://angualr-web-ap-east-1-firsthonourintltd.s3-website.ap-east-1.amazonaws.com
Referer: http://angualr-web-ap-east-1-firsthonourintltd.s3-website.ap-east-1.amazonaws.com/login
Sec-Fetch-Mode: cors
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36
我想我得到了响应,因为响应头部分显示了如下内容
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS
Access-Control-Allow-Origin: http://angualr-web-ap-east-1-firsthonourintltd.s3-website.ap-east-1.amazonaws.com
Connection: keep-alive
Content-Length: 0
Date: Sun, 14 Jun 2020 13:41:43 GMT
Server: nginx/1.16.1
Vary: Origin, Access-Control-Request-Headers
X-Powered-By: Express
但是控制台有问题
Access to XMLHttpRequest at 'http://node-express-env.eba-aqztwrxw.ap-east-1.elasticbeanstalk.com/login' from origin 'http://angualr-web-ap-east-1-firsthonourintltd.s3-website.ap-east-1.amazonaws.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我不知道为什么,两个头都有access-control-allow-origin参数为什么CORS会阻止我
什么是“同源”?
如果两个URL具有相同的方案,主机和端口,则它们具有相同的起源
这两个URL具有相同的起源:
http://example.com/foo.html
http://example.com/bar.html
这些URL的来源与前两个不同
http://example.net-不同域
http://example.com:9000/foo.html-不同端口
https://example.com/foo.html-不同方案
http://www.example.com/foo.html-不同子域
所以我猜AWS EB和AWS S3有一个以上不同的来源URL。 请首先检查这些。如果是,将请求源url添加到您的nodejs API中。 使用此cors库并按照实现
在Express中启用cors