虽然使用Postman将数据通过NodeJS传输到MarkLogic 8没有问题,但使用Angular I无法使其工作。 req.body
会返回{}
。
我尝试过的事情之一就是添加:
app.use(bodyParser.urlencoded({
extended: true
}));
和
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:9040');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
我的控制器中有以下功能:
function putFabriek($fabriek, $http) {
var mlUrl = 'http://localhost:3000/fabriek';
console.log($fabriek);
$http({
method: 'PUT',
url: mlUrl + '?id=' + $fabriek.id,
headers: {'Content-Type': 'application/json'},
data: JSON.stringify($fabriek)
}).success(function(data, status) {
console.log($http.succes);
}).error(function(data, status) {
console.log($http.error);
});
};
在NodeJS中,我有以下内容:
// Fabrieken Puter
app.put('/fabriek', function (req, res) {
var inhoud = req.body;
var fabId = req.query.id;
console.log(inhoud);
db.documents.write(
{ uri: ('/fabrieken/' + fabId + '.json'),
collections: ['examples', 'metadata-examples'],
contentType: 'application/json',
content: inhoud
})
.result(null, function(error) {
console.log(JSON.stringify(error));
});
res.json({ message: 'Fabriek is updated!' });
});
答案 0 :(得分:3)
您正在发送JSON,因此您需要添加相关的JSON正文解析器方法。
app.use(bodyParser.json());