javascript - 使用 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 仍然响应相同的错误......
谢谢您的帮助。干杯。
解决方案
'Access-Control-Allow-Origin':'*'
在响应标头中不在请求标头中将解决问题。由于它需要在响应标头中,因此需要服务器端修改。
推荐阅读
- css - 悬停后变换比例更改位置元素
- c# - 查找两个日期之间的小时数
- python - FLASK_ENV 似乎被忽略(无法进入调试环境)
- bash - for循环子命令中的bash变量扩展
- vba - 是否可以在access中根据combobox.value做动态sql语句?
- c# - 如何在 C# 中将粘贴处理程序添加到 IOleWindow
- visual-studio - Xamarin UWP 应用抛出 System.MissingFieldException:找不到字段:'Xamarin.Forms.VisualElement.StyleProperty'
- pandas - 如何在多索引中为日期时间设置索引?
- python - 如何使用模型将过滤的数据行从表移动到另一个表
- jasmine - 如何在 Jasmine 和 Angular 中测试 ngOnInit 的代码逻辑