【问题标题】:No Access-Control-Allow-Origin header is present on the requested resource. set the request's mode to no-cors to fetch the resource with CORS disabled请求的资源上不存在 Access-Control-Allow-Origin 标头。将请求的模式设置为 no-cors 以获取禁用 CORS 的资源
【发布时间】:2022-11-11 16:08:31
【问题描述】:

已被阻止CORS政策:否'访问控制允许来源'请求的资源上存在标头。如果不透明的响应满足您的需求,请将请求的模式设置为'禁止'获取禁用 CORS 的资源

在网络浏览器中下载 txt 文件的 URL https://google.com/complete/search?client=chrome&q=python

import './App.css';
import {useState} from 'react';

function App() {
  const [Keyword, setKeyword] = useState("");
  const [Result, setResult] = useState([]);

  const findMatch = async () => {
    const getMatch = await fetch("http://google.com/complete/search?client=chrome&q=" + Keyword, {
      method: 'GET',
      headers: {
      'Access-Control-Allow-Origin': true,
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582',
      'Content-Type': 'text/plain',
      },
    })
    console.log(getMatch);
  }

  return (
    <div className="App">
      <input placeholder='Put Keyword' value={Keyword} onChange={(e) => setKeyword(e.target.value)} />
      <button onClick={findMatch}>Search</button>
    </div>
  );
}

export default App;

【问题讨论】:

  • Access-Control-Allow-Origin 是一个响应头,所以永远不要把它放在请求中

标签: javascript reactjs api cors http-headers


【解决方案1】:

CORS 是一种服务器端来源检查服务,您可以在其中允许或禁止某些来源请求您的资源。鉴于此,您的标头选项 'Access-Control-Allow-Origin': true 将在 RESPONSE 标头中从服务器返回,而您尝试将其放入 REQUEST 标头中,这将不起作用。您可以尝试在您的请求中禁用 CORS,尽管这将允许您的请求中的标头更少:

const getMatch = await fetch("http://google.com/complete/search?client=chrome&q=" + Keyword, {
      method: 'GET',
      mode: 'no-cors',
      headers: {
      'Content-Type': 'text/plain',
      },
    })

来源:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options

【讨论】:

    【解决方案2】:

    您可以为此使用 cors 代理服务。例如,cors.sh

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 2017-04-11
      • 2022-07-28
      • 2020-02-13
      • 2017-08-19
      • 2021-07-17
      • 2016-05-20
      相关资源
      最近更新 更多