角度9部署在heroku上的nodejs应用中的CORS错误"/>
[使用角度9部署在heroku上的nodejs应用中的CORS错误
Server.js代码:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors')
const db = require('./DB/db');
const routes = require('./api/routes/routes');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors({
origin: '*'
}));
routes(app);
app.listen(PORT, () => {
console.log(`Server started at ${PORT}`);
});
package.json文件:
{
"name": "LMS_Backend",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"joi": "^14.3.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.9.11",
"nodemailer": "^6.4.6"
}
}
Angular服务文件:
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
const baseUrl = '';
// const baseUrl = 'http://localhost:3000/api/lms_project';
@Injectable({
providedIn: 'root',
})
export class AdminServiceService {
constructor(private http: HttpClient) {}
register(adminDetails) {
console.log(adminDetails);
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json'
});
let options = {
headers: headers,
};
return this.http.post(`${baseUrl}/admin/register`, adminDetails, options);
}
}
错误:
已从起源''到'http://localhost:4200'对XMLHttpRequest的访问已被CORS策略阻止:在所请求的资源上没有'Access-Control-Allow-Origin'标头。
注意:我可以在本地主机上运行应用程序,但在Heroku URL上却给出错误。
回答如下:跨源资源共享(CORS)是一种机制,它使用附加的HTTP标头来告诉浏览器以使Web应用程序在一个来源运行,并从另一个来源访问选定的资源。
您可以从一个HTTPS域向另一个HTTPS域发出CORS请求。如果您发出http请求来调用https服务器,则认为对服务器的篡改数据被认为是不安全的强制请求。
在这里,正如我所见,您正在尝试从本地http访问https服务器,这就是您遇到CORS问题的原因。
更多推荐
[使用角度9部署在heroku上的nodejs应用中的CORS错误
发布评论