在我的node.js api中,我试图将多个值传递到tracking
和carrier
字段中,但是我没有成功。我可以使用单个值(对于tracking
使用1个跟踪号,对于carrier
使用1个运营商代码)来执行此操作,但是对于多个值则不能。我觉得应该有一个循环涉及,但也许我不正确地指出这一点。任何帮助将不胜感激。
Index.html
<script>
function UserParams() {
console.log('UserParams')
var trackingNumber = ['123', '456'];
var carrierCode = ['usps', 'fedex'];
var url = '/api/tracking/retrieve/';
$.ajax({
type: 'GET',
url: url,
data: { tracking: trackingNumber, carrier: carrierCode },
dataType: 'json',
error: function (e) {
console.log('Error Message: ', e.message);
}
});
}
</script>
Controller.js
app.get("/api/tracking/retrieve", (req, res) => {
var carrier = req.query.carrier;
var tracking = req.query.tracking;
console.log('carrier array', carrier);
console.log('tracking array', tracking);
var options = {
method: "GET",
url: 'https://api.example.com/v1/tracking',
qs: { carrier_code: carrier, tracking_number: tracking },
headers:
{
'api-key': process.env.SECRET_KEY_SE,
'accept': 'application/json'
}
}
console.log("Url: ", req.url);
console.log("Query: ", req.query);
res.send("ok");
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('BODY', body)
var trackingData = JSON.parse(body)
table = 'tracking_table';
col = [
'user_id',
'tracking_number',
'carrier_code',
];
val = [
user_id,
trackingData.tracking_number,
options.qs.carrier_code,
];
main.create(table, col, val, function (data) {
res.json({
id: data.insertId,
user_id: user_id,
tracking_number: data.tracking_number,
carrier_code: data.carrier_code,
});
})
}
})
})
终端结果:
carrier array [ 'usps', 'fedex' ]
tracking array [ '123', '456' ]
Url: /api/tracking/retrieve/?tracking%5B%5D=123&tracking%5B%5D=456&carrier%5B%5D=usps&carrier%5B%5D=fedex
Query: { tracking: [ '123', '456' ],
carrier: [ 'usps', 'fedex' ] }
编辑:编辑后的问题以包含更多上下文。
答案 0 :(得分:0)
根据后端是什么,您可以尝试简单地为此目的使用数组,例如
var tracking = ['9361289691090998780245','784644233438'];
var carrier = ['usps','fedex'];
options = {
method: "GET",
url: 'https://api.example.com/v1/tracking',
qs: { tracking_number: tracking, carrier_code: carrier },
headers:
{
'api-key': process.env.SECRET_KEY_SE,
'accept': 'application/json'
}
}
request(options, function (error, response, body) {
if (error) console.error("An error occurred: ", error);
console.log("body: ", body);
});
如果Express提供此服务,则查询字符串将被正确解析,例如
app.get("/api/tracking/retrieve", (req, res) => {
console.log("Url: ", req.url);
console.log("Query: ", req.query);
res.send("ok");
});
这是Express记录的内容;
Url: /api/tracking/retrieve?tracking_number%5B0%5D=9361289691090998780245&tracking_number%5B1%5D=784644233438&carrier_code%5B0%5D=usps&carrier_code%5B1%5D=fedex
Query: { tracking_number: [ '9361289691090998780245', '784644233438' ], carrier_code: [ 'usps', 'fedex' ] }
当然,它取决于API提供程序,因此值得一看的是他们是否拥有有关应如何格式化参数的文档。
答案 1 :(得分:0)
尝试使用功能 split
将字符串跟踪和载波更改为 array➜ rexe git:(master) ✗ ruby -r awesome_print -e "ap 'hello'"
"hello"