【问题标题】:Making a CORS client-side request with Webpack - Node.JS [duplicate]使用 Webpack 发出 CORS 客户端请求 - Node.JS [重复]
【发布时间】:2017-04-14 11:50:45
【问题描述】:

我正在使用 Webpack 来捆绑我的 javascript 代码并在浏览器中使用模块。

我正在尝试获取 URL 的正文 (http://www.redbubble.com);但是,我收到以下错误:

XMLHttpRequest cannot load http://www.redbubble.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. 

这是我捆绑的代码,并请求获取http://www.redbubble.com 的正文 html(包括在我的 ejs 中的脚本标记参考下)

var request = require('request');

var options = {
  url: 'http://www.redbubble.com',
  withCredentials: false
};

function callback(error, response, body) {
    window.console.log("callback is being called");
  if (!error && response.statusCode == 200) {
    alert(body);
  } else {
    window.console.log(error);
  }
}

request(options, callback);

我也在尝试使用我的 app.js 中的 CORS 模块来解决 Acces-Control-Allow-Origin 错误,但这并不好。

app.use(cors({
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  "preflightContinue": false
})); 

为什么这个错误仍然存​​在?又该如何解决?

【问题讨论】:

  • "我也在尝试在我的 app.js 中使用 CORS 模块" — 您的 app.js 正在 localhost:3000 上运行,而不是在 www.redbubble.com 上运行
  • @Quentin 你能澄清一下吗?那我该怎么办呢?
  • 设置标题没有修复错误
  • "设置标题并没有修复错误" — 你是如何更改它们的?您是否为 redbubble 工作并可以访问他们的服务器?
  • 所以我读到:“您无法在客户端代码中执行任何操作来启用 CORS 访问其他人的服务器。”我想弄清楚我现在应该怎么做?

标签: javascript node.js express webpack cors


【解决方案1】:

我猜你在这样的方法中缺少 OTIONS:

app.use(cors({
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE, OPTIONS",
  "preflightContinue": false
})); 

你为什么需要它的解释可以在这里找到:Understanding cors 您需要使 OPTIONS 方法可用,因为它在服务器和客户端之间用于协商调用。

【讨论】:

  • 问题中引用的代码和错误消息都表明它不是预检请求。不需要 OPTIONS。
  • @Quentin 那我该怎么办?
猜你喜欢
  • 2019-01-24
  • 2014-05-23
  • 2021-09-17
  • 1970-01-01
  • 2015-03-02
  • 2021-12-02
  • 2018-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多