如何将json传递给nodejs请求post方法?

时间:2016-11-14 21:23:40

标签: javascript node.js node-modules npm-request

我尝试将json传递给nodejs post方法。但是我收到错误“必须指定搜索查询。”。我已指定搜索字符串并过滤代码。你能告诉导致这个错误的原因吗。

在POSTMAN中使用相同的请求。

//Load the request module
var express = require('express');
var request = require('request');
var app = express();

//Lets configure and request
request({
    url: 'http://host:8080/rest/1.0/search', 
    qs: {query: 'nodejs*'}, 
    method: 'POST',
    json: {
        filter:
        {
            community: ['33862a97-44e5-4de5-9206-db0a61dd83ca'],
            vocabulary: ['b80f3576-0642-4049-bb07-d72a0dd9e3e0','48029bb8-0585-4ed5-afaa-55014aebfcb3'],
            type: {asset:['00000000-0000-0000-0000-000000011001']},
        },
        fields: ['name']

    }
}, function(error, response, body){
    if(error) {
        console.log(error);
    } else {
        console.log(response.statusCode, body);
}
});
app.listen(8080);

1 个答案:

答案 0 :(得分:1)

根据您的postman屏幕截图,您可以通过删除qs: {query: 'nodejs*'}并在json内添加相同代码来尝试以下代码。

//Load the request module
var express = require('express');
var request = require('request');
var app = express();

//Lets configure and request
request({
    url: 'http://host:8080/rest/1.0/search', 
    method: 'POST',
    json: {
        query: 'nodejs*',
        filter:
        {
            community: ['33862a97-44e5-4de5-9206-db0a61dd83ca'],
            vocabulary: ['b80f3576-0642-4049-bb07-d72a0dd9e3e0','48029bb8-0585-4ed5-afaa-55014aebfcb3'],
            type: {asset:['00000000-0000-0000-0000-000000011001']},
        },
        fields: ['name']

    }
}, function(error, response, body){
    if(error) {
        console.log(error);
    } else {
        console.log(response.statusCode, body);
}
});
app.listen(8080);