简体   繁体   English

你如何从本地主机发送跨源请求?

[英]How do you send a cross origin request from localhost?

I have my front end running on localhost:8080 and my server on localhost:3000.我的前端运行在 localhost:8080 上,服务器运行在 localhost:3000 上。 I'd like to send a request from my front end to the server.我想从我的前端向服务器发送一个请求。 When I do, I get the following error:当我这样做时,出现以下错误:

Access to XMLHttpRequest at 'localhost:3000/create-sharable-url' from origin ' http://localhost:8080 ' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. CORS 策略已阻止从源“ http://localhost:8080 ”访问位于“localhost:3000/create-sharable-url”的 XMLHttpRequest:跨源请求仅支持协议方案:http、数据、chrome、chrome - 扩展名,https。

I am using the http protocol, so why would I get this error?我正在使用 http 协议,为什么会出现此错误?

I'm trying to make the request from the localhost protocol, so that error makes me think that it just isn't possible to do.我正在尝试从localhost协议发出请求,所以这个错误让我觉得这是不可能的。 But on the other hand, sending a request from your client to your server in development mode seems like an incredibly common requirement.但另一方面,在开发模式下从客户端向服务器发送请求似乎是一个非常普遍的需求。

Googling around seems to point me in the direction of getting the CORS headers set on the response.谷歌搜索似乎为我指明了在响应中设置 CORS 标头的方向。 I already am setting the headers on my server (using the cors npm package), but I figured I'd give it a go anyway.我已经在我的服务器上设置了标头(使用cors npm 包),但我想无论如何我都会试一试。 It didn't work for me though.虽然它对我不起作用。 The Access-Control-Allow-Origin: * Chrome extension didn't work, nor did running Chrome with the disable web security flag. Access-Control-Allow-Origin: * Chrome 扩展没有工作,也没有运行带有禁用网络安全标志的 Chrome。

Client JS客户端JS

createSharableEquityCalculatorURL: function (storeState) {
  let data = this._constructEquityCalculatorData(storeState);

  return Vue.axios.post(`${process.env.BASE_API_URL}/create-sharable-url`, data);
},

The fact it says "Access to XMLHttpRequest at 'localhost:3000/create-sharable-url " makes me think that in your JS you forgot to put http:// at the start of the target URL.它说“访问 XMLHttpRequest at 'localhost:3000/create-sharable-url ”这一事实让我觉得在你的 JS 中你忘了将http://放在目标 URL 的开头。

Write it out in full in your code ie http://localhost:3000/create-sharable-url在你的代码中完整写出来,即http://localhost:3000/create-sharable-url

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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