NodeJS中POST请求的数据错误

时间:2015-12-27 13:21:20

标签: javascript node.js

这是我在nodejs中的简单服务器应用程序。我的网站处理帖子有问题。

1 post = app什么都不返回 2 post = app返回上一篇文章中的数据

var http = require('http');
var util = require('util');

var tenitem = [];
var dataa;

http.createServer(function (req, res) {
    if (req.method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*' });
        res.end('Hello World\n');
    }

    if (req.method === 'POST') {
        var body = ''
        console.log("POST");
        req.on('data', function (data) {
            body += data;
        });
        req.on('end', function () {
            console.log(body)
            dataa = body;
            http.get('http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=' + dataa, function (api) {
                var bod = '';

                api.on('data', function (chunk) {
                    bod += chunk;
                });

                api.on('end', function () {
                    console.log(bod)
                    tenitem = JSON.parse(bod);
                })
            })
        });

        res.writeHead(200, { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*' });
        res.end(tenitem.lowest_price)
    }
}).listen(port, hostname, function () {
    console.log('Server running');
});

1 个答案:

答案 0 :(得分:0)

tenitem在内部函数中初始化,并且您尝试将其发回。只需在该功能中移动res.end()

api.on('end', function () {
    console.log(bod)
    tenitem = JSON.parse(bod);
    res.writeHead(200, { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*' });
    res.end(tenitem.lowest_price)
})
相关问题