首页 > 解决方案 > 使用 fetch 修复 CORS 问题

问题描述

我被 CORS 问题困扰了一段时间。我一直在检查大量文档,但我仍然无法解决这个问题,我不确定我错过了什么。我认为这是一个经典的获取:

fetch('http://192.168.1.1/osc/commands/execute', {
  method:'POST',
  headers:{
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin':'*' ,
    'X-Requested-With':'xmlhttprequest'
  },
  mode:'cors',
  body:JSON.stringify({
    name: 'camera.startSession',
    parameters: {}
  })
 })
 .then(response => response.json())
 .then(console.log)
}

但我仍然有这个错误:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.1/osc/commands/execute。(原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。 接下来是:跨域请求被阻止:同源策略不允许读取http://192.168.1.1/osc/commands/execute处的远程资源。(原因:CORS 请求未成功) 是否认为标题'Access-Control-Allow-Origin':' '* 应该解决此问题?我已经在 chrome 上使用 Talend API Tester 成功测试了这个请求,但是选项 copy as fetch 仍然响应相同的错误......

谢谢您的帮助。干杯。

标签: javascriptcorsfetch

解决方案


'Access-Control-Allow-Origin':'*'响应标头中不在请求标头中将解决问题。由于它需要在响应标头中,因此需要服务器端修改。


推荐阅读