我试图解析来自网址的一些json数据并将其保存到我的mongoDB模型中。但我似乎无法正确地从body
解析JSON。我怎样才能做到这一点?
代码
router.get('/news', function(req, res){
request({
method: "GET",
url: "URL",
json: true
}, function(err, response, body) {
console.log(err);
res.json(body);
var info = JSON.parse(body);
console.log(info.articles);
})
});
来自api的代码片段
{
"articles": [
{
"title": "this is the title",
"created": "12-09-2015",
"author": "John Doe",
"image": "http://url.com/test.jpg",
"body": "this is the body"
},
{
"title": "this is the title",
"created": "12-09-2015",
"author": "John Doe",
"image": "http://url.com/test.jpg",
"body": "this is the body"
}
]
}
新闻模式
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var newsSchema = new Schema({
title: String,
created: String,
author: String,
image: String,
bodyfull: String
});
module.exports = mongoose.model('news', newsSchema);
答案 0 :(得分:0)
我不确定我到底在你的例子中究竟发生了什么。
但是如果要从节点中的请求主体检索信息,可以从POST请求
所以
var News = require('newsModel'); //wherever it's located
Router.post('/news', function(req,res){
var infoToParse = req.body;
var info = JSON.parse(infoToParse);
var newsItem = new News(info);
newsItem.save(function(err){
if(err) return handleError(err)
});
}
不确定这是否有帮助?我不是节点大师,但这就是我做的事情