我用 Angular 9 创建了我的项目,我将服务器端上传到两个主机,我将请求发送到 Windows 主机,一切正常,但是当我将请求发送到 Linux 主机时,遇到以下错误。
Access to XMLHttpRequest at 'https://exam.com/api/Uni/GetAll' from origin 'http: // localhost: 4200' has been blocked by CORS policy: Response to preflight request does not pass access control check : It does not have HTTP ok status.
可能是什么问题?我是否必须在服务器端或 Angular 中更改托管设置?
顺便说一句,通过我发送请求的帖子,没问题,但是使用 Angular 项目。
@NgModule({
declarations: [
AppComponent, HomeComponent, NewsComponent, MainAdminComponent, PageNotFoundComponentو...
],
imports: [
BrowserModule.withServerTransition({ appId: 'serverApp' }), AppRoutingModule, FormsModule, BrowserAnimationsModule, ReactiveFormsModule,
HttpClientModule, OwlModule, RichTextEditorAllModule, DialogModule,...
],
providers: [
{ provide: DateAdapter, useClass: MaterialPersianDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: PERSIAN_DATE_FORMATS },
{provide:LocationStrategy,useClass:HashLocationStrategy}
],
bootstrap: [AppComponent]
})
答案 0 :(得分:1)
我认为问题出在服务器端(后端主机)。你确定两台主机(windos & linux)上的代码是一样的吗?
我遇到此错误的主要原因是后端设置不正确。
每当您从 frontend
向 backend
发出请求时,因为它们都是两个不同的来源,您就会遇到 CORS 问题。
您必须在后端启用(配置)CORS plocity。
以下是 Node.Js (express)
后端的示例 - 启用所有 CORS 请求:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
完整指南:https://expressjs.com/en/resources/middleware/cors.html
其他网络服务器的另一个有用链接:https://enable-cors.org/server.html
我找到了一个很好的解释 CORS 的工作原理:CORS - Is it a client-side thing, a server-side thing, or a transport level thing?
答案 1 :(得分:0)
这不是前端问题,只要您发送后端需要的标头(例如 jwt 令牌),那么问题应该通过启用 cors 请求来解决。