【问题标题】:Express server receiving POST RequestExpress 服务器接收 POST 请求
【发布时间】:2013-08-29 10:32:56
【问题描述】:

下面是一个 Express 程序


问题:: 我没有在 CLIENT 中得到正确的 JSON 响应

我想知道的::

  • 当我给出一个 来自客户的发布请求
  • 客户端以(Key,Value)pair的形式发送请求
  • 我确定我遇到了问题的请求结构

我该如何解决?


var express = require('express')
  , async = require('async')
  , http = require('http')
  , mysql = require('mysql');

var app = express();

var connection = mysql.createConnection({
    host: 'localhost',
    user: '*************',
    password: "**************",
    database: 'restaurants'
});

connection.connect();

// all environments
app.set('port', process.env.PORT || 1828);


app.get('/RestaurantDesc/:Key',function(request,response,next){

    var keyName=request.params.Key;
    var name_of_restaurants, RestaurantTimings;
    async.series( [
        // Get the first table contents
        function ( callback ) {
            connection.query('SELECT * FROM ',keyName, function(err, rows, fields)
                {
                        console.log('Connection result error '+err);
                        name_of_restaurants = rows;
                        callback();
                });
        },
        // Get the second table contents
        function ( callback ) {
        connection.query('SELECT * FROM RestaurantTimings', function(err, rows, fields)

            {
                    console.log('Connection result error '+err);
                    RestaurantTimings = rows;
                    callback();
            });
        }

   // Send the response
], function ( error, results ) {
    response.json({
        'restaurants' : name_of_restaurants,
        'RestaurantTimings' : RestaurantTimings
    });
} );
} );




http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

有什么想法吗?

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    您没有处理 POST 请求的路由。你应该有类似app.post('/route', function(request, response, next) { ... });的东西。

    您还需要使用 Express 正文解析器从 POST 请求(即app.use(express.bodyParser());)中获取数据。然后你可以在你的中间件函数中访问request.body 的数据。

    【讨论】:

    • 启用 Express 的日志记录以帮助调试也可能很有用,即app.use(express.logger());
    • 这些天你需要单独 npm install body-parser,像这样var bodyParser = require('body-parser') 需要它并像这样使用它app.use(bodyParser())
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 2016-11-14
    • 2017-03-29
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多