Friday, September 15, 2017

Proxy Api Calls in Vue2

The big advantage is we don't have to worry about CORS
https://github.com/prograhammer/vue-example-project#proxy-api-calls-in-webpack-dev-server

npm install --save vue-resource
npm install --save-dev http-proxy-middleware

in build/index.js add
'/service': {
 target: 'http://services.groupkt.com',
 changeOrigin: true, 
 ws: true,   // proxy websockets
 pathRewrite: {
   '^/service/state/': '/state/get/'   // http://localhost:8080/service/state/ => http://services.groupkt.com/state/get/
 }, 
 router: {
 }   
}

If it is configured properly, you will see this when the node server is started.
[HPM] Proxy created: /service  ->  http://services.groupkt.com
[HPM] Proxy rewrite rule created: "^/service/state/" ~> "/state/get/"

in .js file
// send request to http://localhost:8080/service/state/USA/all will be eventually sent to http://services.groupkt.com/state/get/USA/all
this.$http.get('/service/state/USA/all', {})  
        .then(response => {
            this.states = response.body.RestResponse.result
        }, response => {
            console.log("error");
            console.log(response)
      });

https://github.com/hairinwind/myVue/blob/master/src/components/HttpProxy.vue

No comments:

Post a Comment