【问题标题】:Fetch http://localhost:3001/ from Chrome Extension with React使用 React 从 Chrome 扩展中获取 http://localhost:3001/
【发布时间】:2020-09-13 04:13:56
【问题描述】:

我看到了一些类似的问题和解决方案,人们想点击http://localhost:3001/some_url 并使用cors 这样做。

但我的问题有点不同。我的网络应用不是网站,而是网络扩展。

到目前为止,即使使用 cors,我也找不到从 http://localhost:3001/url 获取的方法。

我试过的是:

服务器:

const cors = require("cors");
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.use(
  cors({
    origin: "http://localhost:3001/url" // restrict calls to those this address
    
  })
);

background.js 文件中:

create(urls){
    console.log(urls);
    return new Promise((resolve, reject) =>{
      fetch('https://cors-anywhere.herokuapp.com/'+'http://localhost:3001/url', {
        method: 'POST',
        body: JSON.stringify(urls),
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          "Access-Control-Allow-Origin: *"
        }
      })
        .then(result => result.json())
        .then(json => resolve(json))
        .catch(err => {
          console.log(err);
          reject(err);
        });
    });
  }

我还在packages.json中添加了"proxy": "http://localhost:3001/url"

我仍然收到错误:

Access to fetch at 'http://localhost:3001/url' from origin 'chrome-extension://extension_id' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3001/url' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: reactjs mongodb cors azure-cosmosdb


    【解决方案1】:

    看起来您正在向原点添加路径 /url,但 origin 是:

    Web 内容的来源由方案(协议)、主机定义 (域),以及用于访问它的 URL 的端口

    尝试使用http://localhost:3001 作为原始值。

    【讨论】:

    • 好的。我刚试过。如果我不添加cors-anywhere-heroku... 我只会得到相同的错误,除了/url 。如果我添加cors-anywhere-heroku.... 和http://localhost:3001 我得到cors-anywhere.herokuapp.com/http://localhost:3001:1 Failed to load resource: the server responded
    猜你喜欢
    • 2021-12-17
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 2019-01-07
    • 2016-05-15
    • 1970-01-01
    相关资源
    最近更新 更多