首页 > 解决方案 > 缺少 CORS 错误

问题描述

我意识到这个问题是在 nauseum 被问到的,但我无法找到一个似乎很常见的解决方案。

尝试发出发布请求时,服务器应用程序显示以下响应:

Access-Control-Allow-Headers x-requested-with, Content-Type…accept, client-security-token Access-Control-Allow-Methods POST, GET, OPTIONS, DELETE, PUT Access-Control-Allow-Origin * Access-Control-Max-Age 1000

但出现错误:

> 跨域请求被阻止:同源策略不允许在http://localhost:3000/contact读取远程资源。(原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。

我正在尝试使用 JS fetch 函数发出请求:

  fetch('//<my-app-server.com/endpoint>', {
    method: 'post',
    body: send_data,
    mode: 'cors',
    headers: {
      'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
      'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
    },        
  }).then((result) => {
   console.log('success')
  }).catch((error) =>{
    console.log(error);
  })

我试过有和没有标题。使用托管 apache 主机并且只想打开全局 CORS 请求。不知道我在这里缺少什么。

任何的建议都受欢迎。

标签: javascriptcors

解决方案


错误与在表单提交返回后服务器执行 301 和重定向页面没有 CORS 标头有关。

fetch 跟随页面返回到重定向页面并在 CORS 上失败。


推荐阅读