Search code examples
javascriptajaxcorsxmlhttprequest

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. 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.

I am using the http protocol, so why would I get this error?

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. 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. I already am setting the headers on my server (using the cors npm package), but I figured I'd give it a go anyway. 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.

Client JS

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

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

Solution

  • 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.

    Write it out in full in your code i.e. http://localhost:3000/create-sharable-url