我最近开始学习vue.js并使用vue.js与vue-simple-webpack模板,express和mongo开发了一个简单的应用程序。我使用本地主机来开发和测试应用程序。从Vue应用程序调用运行在不同端口的Vue应用程序的节点快递服务器API
港口应用程序前端运行和服务器在不同的端口(3000)
这是运行我server.js
在那里我有一个简单的API从我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));
})
})
测试了server.js,它的工作原理。看下面的截图。
Vue的应用程序正在使用的WebPack模板的默认配置中运行。我试图调用使用$ HTTP GET如下vue.js文件/products
API结束......
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');
});
}
}
}
但我得到的浏览器控制台下面的错误。
正如你所看到的,即使我使用的端口3000
在server.js
,当我尝试访问/products
API结束,它实际上通过端口8080
去。因此它会抛出一个 http错误。
我的问题是我如何从前端运行在另一个端口的API端。这甚至有可能吗?
我可以在这里使用API Proxying。如果是这样,有人可以指出我正确的方向如何做到这一点,因为网上没有太多的信息可用。
'$ http()'应该允许你指定端口。 – theGleep