简体   繁体   中英

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

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled

The URL downloading a txt file in web browser 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;

CORS is a server-side origin checking service where you can allow or disallow certain origins to request your resources. Given this, your header option 'Access-Control-Allow-Origin': true would be returned from the server in a RESPONSE header, while you're trying to put it in the REQUEST header and this will not work. You can try disabling CORS on your request, although this will allow for less headers in your request:

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

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

You can use a cors proxy service for that. for example, cors.sh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM