【发布时间】:2017-04-17 07:14:07
【问题描述】:
所以我有一个运行 Apache、Node 和 Mongo 的 Digital Ocean Ubuntu VPS。我可以通过服务器上的 CURL 从我的数据库中返回数据。节点后端肯定在 3000 端口上运行。
我的 React 前端使用 Fetch,我目前将它指向 localhost:3000。这是错的吗?
对于我的前端 React 包应该在我的服务器上相对于我的 server.js 的位置,我也有点困惑。这有关系吗?
我可以通过我的域访问前端,只是它不像我在本地处理它时那样抓取数据。我必须在我的 server.js 中遗漏一些东西才能让他们互相交谈......
我读到了 Apache VirtualHost 以及它如何成为在单个 Apache 服务器上运行节点应用程序的必要组件。如果您对此有所了解,请告诉我。
这是来自前端的 httpservice.js 文件:
var Fetch = require('whatwg-fetch');
var baseUrl = 'http://localhost:3000';
var service = {
get: function(url) {
return fetch(baseUrl + url)
.then(function(response) {
return response.json();
});
},
post: function(url, ingredient) {
return fetch(baseUrl + url, {
headers: {
'Accept': 'text/plain',
'Content-Type': 'application/json'
},
method: 'post',
body: JSON.stringify(ingredient)
}).then(function(response) {
return response;
});
}
};
module.exports = service;
这是我后端的 server.js:
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bodyParser = require('body-parser');
var app = express();
mongoose.connect('mongodb://admin:admin123@127.0.0.1:27017/food?authSource=admin');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var usersSchema = new Schema({
// _id: String,
id: String,
vote: Number
});
var bkyes = mongoose.model('bkyes', usersSchema);
app.get('/bkyes', function(req, res) {
bkyes.find({}, function(err, bkyes) {
res.send(bkyes);
});
});
app.listen(3000);
非常感谢您的任何见解,欢迎和赞赏所有人!!!
【问题讨论】:
-
客户端 index.html 文件如何调用它需要的所有必要的 JavaScript 文件/库?您的问题在这里不是很清楚。
-
它是一个 React 前端,因此 httpservice.js 文件只定义了在应用程序的其他不相关部分中使用的 GET 和 POST 函数。 index.html 只是一个普通的 index.html,它调用了一个 React bundle.js。
-
我假设您只在 chrome 的本地主机上运行此程序(客户端和服务器)。当您检查 chrome 中的代码时,您是否在控制台中看到任何错误?网络选项卡上的所有元素是否都正确加载?您的问题到底是什么?
-
没有一切都在 DigitalOcean VPS 上。当我将
var baseUrl = 'http://localhost:3000';更改为var baseUrl = 'http://MY_SERVER_IP:3000';时,它仍然没有找到任何东西。我将更改我的问题以表明此服务器是不在本地运行的 VPS。我的问题是我错过了什么。感谢您的帮助!
标签: javascript node.js reactjs express