2016-05-31 67 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調用。

相關問題