Calling a Node.js server with Vue.js Calling a Node.js server with Vue.js vue.js vue.js

Calling a Node.js server with Vue.js


This basically has nothing to do with Node or Vue and everything to do with how security in the browser is implemented. CORS is not a workaround. Read up on CORS to see why it is needed. This question of mine, which is quite similar to yours, has some good info in the answers sections as well. To be able to call an API without using CORS it needs to run on the same host, port and protocol, otherwise it will be blocked by your browser.

Years ago, before the advent of CORS, you needed to use JSONP to achieve the same. You can of course have a look at it to see how this works, but nowadays there is very little need for that technique as we have proper cross-domain support in the form of CORS.

Regarding your question in one of the comment sections on "How do people call API's when working with Vue.js?", they do one of the following:

  1. Run the API on another server (such as api.mydomain.com), but set the CORS headers on the response.
  2. As above, but the client and server wraps responses using the JSONP method mentioned above.
  3. Run the API on the same server as the one serving pages. This means api calls will be done against an endpoint such as localhost:8080/api
  4. Twist on #3: just proxy calls coming in on the server to another server. Meaning you can have your api server running elsewhere, but your main server that is accepting calls on /api will just send these requests on the the next server after stripping off the /api prefix. Usually, people either setup an Apache or Nginx instance in front of your app server and do the actual proxying on that, but you can also do it in your app server, using something like node-proxy.

You can probably read this through the lines already, but save yourself some trouble (and time) and just use CORS :) @trquoccuong has the details on doing this in his answer.


CORS problems, you can use cors node module or add request header

if use Express

res.header('Access-Control-Allow-Origin', 'http://localhost:8080');res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

if use http module

res.setHeader