Calling node express server API from Vue application running in a different port

孤人 提交于 2019-12-08 02:32:42

问题


I recently started learning vue.js and currently using vue.js with vue-simple-webpack template , express and mongo to develop a simple application . I am using localhost to develop and test the application.

application front-end runs in port 8080 and the server is running in a different port (3000)

Here is my server.js where i have a simple api to get data from my localdb

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const mongodb = require('mongodb');
const bodyParser= require('body-parser');
const app = express();
var db;

var URL='mongodb://localhost:27017/'+'mydb';
console.log(URL);

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())

MongoClient.connect(URL, (err, database) => {
  if (err) 
    return console.log(err);
  db = database;
  app.listen(3000, () => {
    console.log('listening on 3000');
  })
})

app.get('/products', (req, res) => {
    db.collection('products').find().toArray(function(err, results) {
    console.log(results)
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify(results));
    })
})

tested the server.js , it works . see below screenshot.

Vue application is running in http://localhost:8080/ using the webpack template's default configuration. i am trying to call the /products api end from the vue.js file using $http get as follows...

export default {
  name: 'Products',
  methods: {
        get: function() {
            // GET request
            this.$http({
                url: '/products',
                method: 'GET'
            }).then(function(response) {
                console.log('ok');
            }, function(response) {
                console.log('failed');
            });
        }
    }
}

But i get the following error in the browser console.

As you can see , even though i am using the port 3000 in server.js , when i try access the /products api end , it actually goes through port 8080. Therefore it throws a 404 http error .

My question is how i can access the API end from within the front-end which runs in a different port. Is that even possible ?

Can i use API Proxying here . If so , can somebody point me in the correct direction on how to do it since there are not much info available on the web.


回答1:


You can use proxy configuration provided by webpack.

Docs: https://webpack.js.org/configuration/dev-server/#devserver-proxy

snippet config:

proxy: {
  "/products": "http://localhost:3000/products"
}

A better practice would be forwarding /api/* requests to http://host:port/api/* urls.



来源:https://stackoverflow.com/questions/46792214/calling-node-express-server-api-from-vue-application-running-in-a-different-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!