将变量传递给NodeJS中的http.request。

huangapple go评论63阅读模式
英文:

Pass variable to http.request in NodeJS

问题

如何传递和检索在Node.js中的http.request()函数中的变量。

var URL = 'parent/test';
var isParentSenior = true;
var output = '';
var options = {
  host: config.ip,
  path: config.rest_prefix + URL,
  method: 'POST',
  rejectUnauthorized: false,
  headers: {
    'Authorization': token,
    'Content-Type': 'application/json;charset=UTF-8',
    'Content-Length': Buffer.byteLength(input, 'utf8'),
    'Browser': userUtil.detectBrowserNameAndVersion(req.headers['user-agent']),
    'ip_address': req.headers['x-forwarded-for']
  }
};
var reqPost = https.request(options, function (resPost) {
  resPost.on('data', function (d) {
    output = output + d;
  });
  resPost.on('end', function () {
    logger.info('Final POST result***:\n' + output);
  });
});

用于检索isParent变量的POST方法。

@POST
@Path("parent/test")
public Response addParent(@Context HttpServletRequest request, @Context HttpServletResponse response) {
  // 如何获取变量isParentSenior
}
英文:

How to pass and retrieve an variable to http.request() in nodejs.

var URL = 'parent/test';
var isParentSenior = true;
var output = '';
var options = {
host: config.ip,
path: config.rest_prefix + URL,
method: 'POST',
rejectUnauthorized: false,
headers: {
'Authorization': token,
'Content-Type': 'application/json;charset=UTF-8',
'Content-Length': Buffer.byteLength(input, 'utf8'),
'Browser': userUtil.detectBrowserNameAndVersion(req.headers[`user-agent`]),
'ip_address': req.headers[`x-forwarded-for`]
  }
};
var reqPost = https.request(options, function (resPost) {
                resPost.on('data', function (d) {
                    output = output + d;
                });
                resPost.on('end', function () {
                    logger.info('Final POST result***:\n' + output);

Post Method to retrieve the isParent variable.

@POST
@Path("parent/test")
public Response addParent(@Context HttpServletRequest request, @Context HttpServletResponse response){
  // How to get the variable isParentSenior
}

答案1

得分: 0

如果您有兴趣遵循REST原则,使用POST发送数据的最佳方式将取决于请求的操作以及这些数据的含义。如果您在服务器上创建一个新的父记录,而isParentSenior是该新记录的一个属性,那么将数据作为POST请求的主体中的JSON序列化对象发送将是合适的。但是,要创建一个新的记录,我假设您可能需要比只有一个字段更多的数据。但是,仅有这个字段时,它会如下所示:

const URL = 'parent/test';
const isParentSenior = true;
const options = {
    host: config.ip,
    path: config.rest_prefix + URL,
    method: 'POST',
    rejectUnauthorized: false,
    headers: {
        'Authorization': token,
        'Content-Type': 'application/json',
    }
};

const reqPost = https.request(options, function (resPost) {
    let output = '';
    resPost.on('data', function (d) {
        output = output + d;
    });
    resPost.on('end', function () {
        logger.info('Final POST result***:\n' + output);
    });
});
const postData = {
    isParentSenior
};
reqPost.write(JSON.stringify(postData));
reqPost.end();

然后,您的服务器将收到包含JSON.stringify(postData)结果的POST请求主体,并需要解析该JSON以访问生成的对象中的isParentSenior属性。

如果isParentSenior变量是某个查询规范的一部分(如果这是一个在服务器上创建新记录的POST请求,则可能不太可能),那么您可以将其作为路径中的文本发送,例如/parent/test/1/parent/test/0,或者将其作为查询字符串的一部分发送,例如/parent/test?isParentSenior=1/parent/test?isParentSenior=0

英文:

Well, if you're interested in following REST principles, the best way to send the data with a POST would depend upon what the request is doing and what this data means. If you're creating a new parent record on the server and isParentSenior is one of the properties of that new record, then it would be appropriate to send the data as a JSON-serialized object in the body of the POST request. But, to create a new record, I would assume you probably need more data than just that one field. But, with just that one field, here's how it would look:

const URL = 'parent/test';
const isParentSenior = true;
const options = {
    host: config.ip,
    path: config.rest_prefix + URL,
    method: 'POST',
    rejectUnauthorized: false,
    headers: {
        'Authorization': token,
        'Content-Type': 'application/json',
    }
};

const reqPost = https.request(options, function (resPost) {
    let output = '';
    resPost.on('data', function (d) {
        output = output + d;
    });
    resPost.on('end', function () {
        logger.info('Final POST result***:\n' + output);
    });
});
const postData = {
    isParentSenior
};
reqPost.write(JSON.stringify(postData));
reqPost.end();

Your server will then get the POST request with a body that contains the result of JSON.stringify(postData) and it will have to parse that JSON so it can access the isParentSenior property in the resulting object.


If the isParentSenior variable is part of some query specification (less likely if this is a POST that is creating a new record on the server), then you would send it as text in the path as in /parent/test/1 or /parent/test/0 or you could send it as part the query string as in /parent/test?isParentSenior=1 or /parent/test?isParentSenior=0.

huangapple
  • 本文由 发表于 2023年6月5日 11:55:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定