【问题标题】:Problem with CORS - Angular, problem with XMLHttpRequestCORS 的问题 - Angular,XMLHttpRequest 的问题
【发布时间】:2022-01-14 06:34:52
【问题描述】:

我想调用一个 API,在我的后端(节点)chrome 控制台中这样说:

CORS 策略已阻止从源“http://localhost:4200”访问“http://127.0.0.1:4201/api//listar_clientes_filtrado_admin”处的 XMLHttpRequest:请求标头字段 content.type 不允许通过预检响应中的 Access-Control-Allow-Headers。

问题是 HttpErrorResponse 不允许我使用 API。

这是我想使用的方法:(ClienteController)

const listar_clientes_filtrado_admin = async function (req, res) {
let registro = await Cliente.find();
res.status(200).send({ data: registro }); }

即使我在我的 app.js(后端)中使用它,但它不起作用。

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
    res.header('Allow', 'GET, PUT, POST, DELETE, OPTIONS');
    next();
});

其他部分:

(Cliente.js)

    //GET
api.get('/listar_clientes_filtrado_admin',
    clienteController.listar_clientes_filtrado_admin
);

(Cliente.service.ts) - 前角

  listar_clientes_filtrado_admin(): Observable<any> {
let headers = new HttpHeaders().set('Content.Type', 'application/json');
return this._http.get(this.url + '/listar_clientes_filtrado_admin', {headers: headers});}

(组件.ts)

ngOnInit(): void {
this._clienteService.listar_clientes_filtrado_admin().subscribe(
  response => {
    console.log(response);
  },
  error => {
    console.log(error);
  }
)

【问题讨论】:

  • Content.Type 是一个错字。那应该是Content-Type
  • 上帝保佑你,我的男人

标签: node.js angular


【解决方案1】:

尝试像这样添加中间位置:

 var cors = require('cors')
 var app = express()

 app.use(cors())`

它启用了所有 cors 请求。

当然你需要先运行npm i cors才能安装它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-06
    • 2021-03-05
    • 2020-11-23
    • 2018-07-17
    • 2021-08-22
    • 2017-06-20
    • 2019-02-05
    • 2015-08-23
    相关资源
    最近更新 更多