Calling node express server API from Vue applicati

2019-06-05 00:04发布

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.

enter image description here

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.

enter image description here

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条回答
走好不送
2楼-- · 2019-06-05 01:03

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.

查看更多
登录 后发表回答