NodeJS Express 4中的查询字符串变量仍然为空

vatpfxk5  于 2023-01-01  发布在  Node.js
关注(0)|答案(4)|浏览(133)

stackoverflow上按照以下建议编写简单服务器:

    • 剩余API. js:**
const express = require('express');
const bodyParser = require('body-parser')

// Initialize RESTful server
const app = express();

app.set('port', (process.env.PORT || 5000));
app.use(bodyParser.json() );                        // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({extended: true}));   // to support URL-encoded bodies

// Spin up the server
app.listen(app.get('port'), function() {
    console.log('running on port', app.get('port'))
});

app.post('/bookinghandler', function (req, res) {
    let senderId = req.query.sender;
    let email = req.query.email;
    let hotelName = req.query.hotelName;
    let confirmNumber = req.query.confirmNumber;
    let start = req.query.startDate;
    let end = req.query.endDate;
}
    • 应用程序js:**
// This loads the environment variables from the .env file
require('dotenv-extended').load();

const builder = require('botbuilder');
const restify = require('restify');

// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
   console.log('%s listening to %s', server.name, server.url); 
});

// Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});

// Listen for messages from users 
server.post('/api/messages', connector.listen());

var bot = require("./bot")
bot.InitializeBot(connector);

// Load REST API module
var restApi = require("./rest_api");

并希望通过查询字符串获取参数(URL中的示例请求:bookinghandler?sender=100000250242810&email=some@email.com&hotelName=Grand Hotel&confirmNumber=654321&startDate=2017-10-11&endDate=2017-10-15)。
但是req.paramsreq.param()req.bodyreq.query仍然是空的。我做错了什么?是否只能通过require('url')require('qs')进行?如果我只想通过快递进行?

hmmo2u0o

hmmo2u0o1#

使用2个REST框架时出现问题:表达和retify。需要使整个应用程序作为retify或表达应用程序。之前我有一个retify服务器和另一个表达服务器内创建(只是举了不同的例子)。通常需要使用一个或另一个,而不是两者兼而有之。

修改的应用程序js:

// This loads the environment variables from the .env file
require('dotenv-extended').load();

const builder = require('botbuilder');
const restify = require('restify');

// Setup Restify Server
var server = restify.createServer();
server.use(require('restify-plugins').queryParser());
server.listen(process.env.port || process.env.PORT || 3978, function () {
   console.log('%s listening to %s', server.name, server.url); 
});

// Index route
server.get('/', function (req, res) {
    res.send('My chat bot')
});

// Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});

// Listen for messages from users 
server.post('/api/messages', connector.listen());

var bot = require("./bot")
bot.InitializeBot(connector);

// Load REST API module
var restApi = require("./rest_api");

// POST request from webview page
server.post('/bookinghandler', restApi.BookingHandler);

修改后的rest_API.js:

const service = require("./service");

module.exports.BookingHandler = async function (req, res, next) {
    let senderId = req.query.sender;
    let email = req.query.email;
    let hotelName = req.query.hotelName;
    let confirmNumber = req.query.confirmNumber;
    let start = req.query.startDate;
    let end = req.query.endDate;

    res.send(200);  // Success
    return next(false);
};
vsikbqxv

vsikbqxv2#

app.post('/bookinghandler', function (req, res) {
       let senderId = req.query.sender;
       let email = req.query.email;
       let hotelName = req.query.hotelName;
       console.log(req.query, senderId, email, hotelName)
})

在我的终端中打印此输出
第一个月

alen0pnh

alen0pnh3#

我能够通过使用JSON.parse克服res.query未定义的问题
常量查询值= JSON.parse(请求查询.queriesHere);控制台日志(查询值);

hs1ihplo

hs1ihplo4#

无论何时,当一个请求带有查询时,这些查询必须存在于url中,以便服务器能够识别它们。
下面是一个示例代码。你需要在html表单中添加查询到action。你也可以使用&分隔它们。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form action="/as/?sender=321&email=myemail@email.com" method="post">
      <input type="text" name="myName" value="">
      <input type="submit" name="" value="ssss">
    </form>
  </body>
</html>

这里是app.js

app.post('/bookinghandler', function (req, res) {

    var senderId = req.query.sender;
    var email = req.query.email;
    console.log('senderId = ' + senderId + ' email = ' + email);
    res.end("got the info");
});

现在,你会问我这样做的目的是什么,因为我们已经在 * form * 中定义了它们。好吧,真正的网站不会这样做。如果你想评估你的查询,你需要让它们*空白,并查看用户在浏览器上是否有任何cookie。
这是html表单

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form action="/as/?sender=&email=" method="post">
      <input type="text" name="myName" value="">
      <input type="submit" name="" value="ssss">
    </form>
  </body>
</html>

这是我们的应用程序

app.post('/bookinghandler', function (req, res) {
    if(req.session.user.id){  //checking the cookies if the user is logged in/exists
       var senderId = req.query.sender;
       var email = req.query.email;
    }else{
     res.send("you haven't logged in");
     return false;
    }

    console.log('senderId = ' + senderId + ' email = ' + email);
    res.end("got the info");
});

有关cookie的节点模块的更多信息,请参见here

结论

表单查询大多是额外的工作,只需使用req.body和cookie,req.session对象就可以轻松完成,除非客户端和服务器之间有额外的数据需要传输,否则人们通常不会使用它。

更新

参数在node.js中定义如下/:param
如果要使用参数

app.get('/bookinghandler/:myParam/?queriesHere='){
   console.log(req.params.myParam + "   and the query: " + req.query.queriesHere);

res.send(req.params.myParam + "   and the query: " + req.query.queriesHere);
}

添加此代码,然后复制并转到此URL localhost:5000/bookinghandler/hereisaparam/?queriesHere = 123
确保添加端口
如果是服务器应用程序,则创建另一个node.js文件,然后运行这两个文件

    • 其他文件. js**
var request = require('request');
request('http://localhost:5000/bookinghandler/hereisaparam/?queriesHere=123', function (error, response, body) {
  if(error){
console.log(error):
return false;
}
  console.log('body:', body); // Print the data
});

在服务器运行时运行此文件。

相关问题