我正在尝试使用Node.js创建一个简单的网站!我在服务器上安装了node.js,我设置了DNS并启动了我的服务器。在按钮上单击POST HTTP请求“/ buildRequest”应发送到服务器。在此路径中,应调用外部函数,该函数返回包含
的对象
ErrorMessage(一个像错误的对象:“这是一个错误”)或文件的路径(字符串)。如果我通过localhost:8888(我正在使用的端口)进入页面,它的工作正常。该路线将被调用。但是,如果我使用DNS名称访问网站并单击按钮,页面上会显示:
“无法加载资源:服务器响应状态为404(未找到)”
Server.js
var express = require('express');
var bodyParser = require("body-parser");
var dbFunc = require("./dbFunctions.js");
var util = require('util');
var app = express();
var path = require('path');
var fs = require('fs');
var port = 8888;
var http = require('http');
http.globalAgent.maxSockets = 1000;
//allow to use body-parser
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
//allow to use static files
app.use(express.static("public"));
//listen to smth
app.post('/buildRequest', function (req, res) {
//buildrequest call was succ
var main = dbFunc.main(req.body.dbParameter, function (data) {
var result = data;
res.send(result);
});
});
//start server
app.listen(port);
console.log("Server running on port" + port);
单击特定按钮时触发的客户端js函数:
function callServerSideScript(dbParameter) {
//do check here if a value is missing
db = document.getElementById(dbParameter).value;
httpRequest = new XMLHttpRequest()
httpRequest.open('POST', '/buildRequest')
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send("dbParameter=" + db);
httpRequest.onload = function () {
if (this.status >= 200 && this.status < 400) {
try {
//if try is successfull response is an object. Return the object as string(error message)
var test = JSON.parse(this.response);
alert(this.response);
} catch (error) {
//is not an object,means its a string = download
window.open("/download");
}
} else {
// We reached our target server, but it returned an error
}
};
httpRequest.onerror = function () {
// There was a connection error of some sort
};
}
为什么路由在服务器上使用localhost而在服务器外访问网站时不能“远程”?
编辑: 我的文件夹结构如下所示: main.js包含客户端函数(比如执行HTTP请求)
.
+--public
| + index.html
| + <someother html files>
| + main.js
|
+-- server.js
|
|
+-- dbFunctions.js
问候