【问题标题】:ExpressJS get post parameter and usage of external javascript functionExpressJS获取post参数和外部javascript函数的使用
【发布时间】:2018-03-28 10:35:27
【问题描述】:

我试图创建一个带有一些服务器端功能的简单网页,但不知何故,有两件事没有按预期工作。

通过 html 按钮即时运行执行 http post 请求的客户端 javascript。
客户端javascript

httpRequest = new XMLHttpRequest()
httpRequest.open('POST', '/test2')
httpRequest.send(var1,var2,var3,var4);

服务器.js

var express = require('express');
var bodyParser = require("body-parser");
var dbFunc = require("./dbFunctions.js");
var app = express();
var path = require('path');
var port = 8888;
//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('/test2', function (req, res) {
console.log("worked");
});
//start server

app.listen(port);
console.log("Server running on port" + port);

我的服务器检测到这个 post http 请求并执行“console.log”,但我如何从 http.request 获取参数作为变量?我尝试使用 bodyParser 但不知何故我的对象总是空的。

另一件事是,我创建了另一个 Javascript 文件(dbFunctions.js)并在服务器文件中实现了它,但是如果我尝试运行一个函数(例如 dbFunc.test("hello")),它会显示“dbFunc.测试不是函数”。

dbFunctions.js

function DBFunctions(){
    function test(a){
        console.log(a);
    }
}

我也尝试过这样做,但这给了我同样的错误。

function test(a){
console.log(a);
}

有人可以给我一个提示或告诉我我缺少什么吗?

【问题讨论】:

标签: javascript node.js http express


【解决方案1】:

答案1:

您将数据发送到 post 请求的方式是错误的,您应该以以下格式发送, xhttp.send("val1=val1&val2=val2");

httpRequest = new XMLHttpRequest()
httpRequest.open('POST', '/test2')
httpRequest.send(var1=var1&var2=var2&var3=var2&var3=var3);

要像 HTML 表单一样 POST 数据,请使用 setRequestHeader() 添加 HTTP 标头。在 send() 方法中指定要发送的数据:

httpRequest = new XMLHttpRequest()
httpRequest.open('POST', '/test2')
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send(var1=var1&var2=var2&var3=var2&var3=var3);

在您的server.js 中,使用req.body 获取这些值。

app.post('/test2', function (req, res) {
    console.log("worked");
    console.log(req.body)
  });

XMLHttp request example

答案2:

从您的 dbFunctions.js 文件中,您应该使用 node js 中的模块导出来导出您的函数。

dbFunctions.js:

var exports = module.exports = {};

exports.test = function(a) {
  console.log(a);
};

你也可以这样做,

module.exports = {
  test: function(a) {
    console.log(a)
  },
}

现在在您的 server.js

var dbFunc = require("./dbFunctions.js");

dbFunc.test();

Node js module exports

【讨论】:

    【解决方案2】:

    您发布的所有变量都将在req.body 尝试console.log(req.body) 中可用。

    其次,您很可能没有从dbFunction.js 导出test 函数,这就是为什么得到“dbFunc.test 不是函数”的原因,因为dbFunc.testundefined

    注意:正如其中一条评论所述,您需要以正确的方式使用httpRequest.send(var1,var2,var3,var4);。它不需要多个参数。

    点赞:httpRequest.send("var=var1&var1=var2")

    请参考:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      • 2020-07-08
      • 2014-03-27
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多