LocalHost、Angular 11 ( https://localhost:4200) 和 Node API ( https://localhost:3001) 都使用 OpenSSL,浏览器是 Chrome。为了解决这个问题Status: CORS error(由于端口不同),我按照这个添加 Proxy,在 Angular 的控制台中得到了这个
[HPM] 尝试将请求 /somewhere1 从 localhost:4200 代理到 https://localhost:3001 (DEPTH_ZERO_SELF_SIGNED_CERT) 时出错 ( https://nodejs.org/api/errors.html#errors_common_system_errors )
以下没有帮助:
chrome://flags/#allow-insecure-localhost 启用。process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";到 Node API 的 server.js。代理.conf.json
{
"context":
[
"/path1",
"/path2"
],
"target" : "https://localhost:3001",
"secure": true,
"changeOrigin": true,
"rejectUnauthorzied": false,
"logLevel": "info"
}
Run Code Online (Sandbox Code Playgroud)
角度.json
"serve": {
...
"options": {
"browserTarget": "myapp:build",
"ssl": true,
"proxyConfig": "src/proxy.conf.json"
Run Code Online (Sandbox Code Playgroud)
调用API:
private http: HttpClient;
const httpOptions =
{
headers: new HttpHeaders({'Content-Type': 'application/json'}),
rejectUnauthorized: false
};
this.http.post<any[]>("/somewhere1/hello", {}, httpOptions).subscribe
Run Code Online (Sandbox Code Playgroud)
相信这就是 Angular 的结局。
经过几天的挫折,我终于能够解决所有问题,并将解决方案发布在这里,希望能帮助别人转发。
环境:
解决方案:
.crt文件.keylocalhost到hosts文件。proxy.conf.js(或具有一致格式的 .json 文件)并将其包含到 angular.json 文件中。httpOption为每个单独的 http 调用指定。server.js.我的 Proxy.conf.js:
const PROXY_CONFIG =
[
{
context:
[
"/path1",
"/path2",
...
],
"target" : "https://localhost:3001", // I use 3000 for non-SSL
"changeOrigin": true, // helps on CORS Error in F12
"logLevel": "debug",
"rejectUnauthorzied": true, // or false if ok for you
"secure": false, // PROD must be "true", but DEV false else "UNABLE_TO_VERIFY_LEAF_SIGNATURE"
"strictSSL": true, // false is default
"withCredentials": true // required for Angular to send in cookie
}
]
module.exports = PROXY_CONFIG;
Run Code Online (Sandbox Code Playgroud)
我的 Angular.json:
"architect": {
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "myapp:build",
"ssl": true,
"proxyConfig": "src/proxy.conf.js"
...
Run Code Online (Sandbox Code Playgroud)
我的服务器.js:
const fs = require("fs");
// following are the two files mentioned in No.5
const HttpSOptions =
{
key: fs.readFileSync('ssl\\server.key'),
cert: fs.readFileSync('ssl\\server.crt')
}
const httpSServer = httpS.createServer(HttpSOptions, app);
httpSServer.listen(3001, ()=>{console.log('httpS is on 3001');});
Run Code Online (Sandbox Code Playgroud)
要验证Chrome完全信任证书,请在 Chrome 中打开您的 API URL 调用之一,例如http://localhost:3001/path1/func/xyz,您不应该看到此内容
| 归档时间: |
|
| 查看次数: |
3912 次 |
| 最近记录: |