2016-08-04 83 views
0

在ajax調用之下進行時,我沒有在節點服務器端看到任何發佈數據。在節點服務器中看不到發佈數據

$.ajax({ 
    type: "POST", 
    url: window.location.origin + "/api/books", 
    data: { 
     title: "Javascript some good partd", 
     author: "Douglas crockford", 
     releaseDate: new Date(2013, 4, 2).getTime() 
    }, 
    dataType: "json", 
    success: function(data) { 
     console.log(data); 
    } 
}); 

做了一些搜索之後,我發現它可能是因爲body-parser的配置,但無法正確解決。請在下面找到節點服務器配置。

app.configure(function() { 
    app.use(bodyParser()); 
    app.use(bodyParser.urlencoded()); 
    app.use(bodyParser.json()); 
    app.use(express.methodOverride()); 
    app.use(app.router); 
    app.use(express.static(path.join(application_root, 'site'))); 
    app.use(express.errorHandler({dumpExceptions: true, showStack: true})); 
}); 

和API調用:

app.post('/api/books', function (req, res) { 
    console.log(req.body); 
    var book = new BookModel({ 
     title: req.body.title, 
     author: req.body.author, 
     releaseDate: req.body.releaseDate 
    }); 
    return book.save(function (err, response) { 
     if (!err) { 
      return res.send(book); 
     } else { 
      console.log(err); 
     } 
    }); 
}); 

req.body被記錄爲不確定。任何人都可以請幫忙調試這個問題?

回答

1

刪除app.configure函數。

它內部的所有代碼都可以保留在該文件中。

我最好的猜測是它不會觸發該功能。

我傾向於使用這個代碼

var bodyParser = require('body-parser'); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true })); 
+0

感謝dsharris!我能夠使用此代碼來處理它。 – user3400887

相關問題