2016-05-31 41 views
0

下面是我的服务器的代码node.js服务器如何访问ajax请求的数据?

/* GET tone. */ 
router.post('/tone', function(req, res, next) { 
    console.log("what is the body" + req.body.data); 
    tone_analyzer.tone({ text: req.body.data }, function(err, tone) { 
    console.log(req.body.data); 
    if (err) { 
     console.log(err); 
    } else { 
     res.send(JSON.stringify(tone, null, 2)); 
    } 
    console.log(req); 
    }); 
}); 

我的阿贾克斯队在HTML页面中调用。

function toneAnalysis(info){ 
    $.ajax({ 
    url: 'http://localhost:3000/tone', 
    type: 'POST', 
    data: info, 
    success: function(res) { 
     console.log("testing " + info); 
    }, 
    error: function(xhr, status, errorThrown) { 
     console.log(status); 
    } 
    }) 

服务器无法检索req.body.data。当我试图控制台登录时,它总是打印未定义的。有人能帮我解决这个问题吗?谢谢。

更新: The printed req.body after I used body parser

+0

它应该是req.body。记录下来,看看它是否定义。您可能需要使用body-parser。 –

+0

其次,您可能需要body解析器的注释,如果它==='string',也看typeof(req.data),那么您可能需要JSON解析它。 –

+0

http://expressjs.com/en/4x/api.html#req.body –

回答

0

您的请求主体将在req.body

如果是JSON,您可以使用

let bodyParser = require('body-parser'); 
    const app = express(); 
    app.use(bodyParser.json()); 

router.post('/tone', function(req, res, next) { 
    console.log("what is the body" + req.body); 
    tone_analyzer.tone({ text: req.body}, 
    function(err, tone) { 
    // your code here 
} 
0

你有这个在你的服务器配置?

app.use(express.bodyParser()); 

这允许您解析JSON请求。

+0

我在我的app.js上有这行代码 –

+0

你的package.json文件里有bodyparser吗? @estherfang –

+0

@HoussemYahiaoui是,“依赖关系”:{0} {0} {0} {0} {“body-parser”:“〜1.13.2”, “cookie-parser”:“〜1.3.5”, “debug”:“〜2.2.0 “, ”express“:”〜4.13.1“, ”jade“:”〜1.11.0“, ”morgan“:”〜1.6.1“, ”serve-favicon“:”〜2.3.0 “ } –

1

就像上面提到的,你可以使用BodyParser,你可以下载并使用安装NPM像这样的答案:

# npm install bodyparser --save 

然后返回到您的$就通话,您发送代表的一些数据在数据对象,所以使用BodyParser你可以只需要发送的对象的访问,因为BodyParser添加另一个目的是在REQ对象的NodeJS和它的所谓身体,所以如果你想使用BodyParser你可能会要做到这一点,像这样来访问所有已发送邮件:

const app = require('express')(); 
    let bodyParser = require('body-parser'); 

    // add a new middleware to your application with the help of BodyParser 
    // parse application/x-www-form-urlencoded 
    app.use(bodyParser.urlencoded({ extended: false })); 

    // parse application/json 
    app.use(bodyParser.json()); 

    //Configure the route 
    router.post('/tone', (req, res, next) => { 
    console.log("what is the body" + req.body.data); 
    tone_analyzer.tone({ text: req.body.data}, (err, tone) => { 
     console.log(req.body.data); 
     if (err){ 
      console.log(err); 
     } 
     else{ 
      res.send(JSON.stringify(tone, null, 2)); 
     } 
     console.log(req); 
    }); 
    }); 

现在使用BodyParser,当你处理你的XHR事情可以变得很容易或HTTP调用。