如何使用节点js将字符串变量作为参数传递给REST API调用

Pre*_*rem 4 node.js

var express = require('express');
var app = express();

// Get Pricing details from subscription
app.get('/billingv2/resourceUri/:resourceUri', function(req, res) {

    var pricingDetail = {}

    pricingDetail.resourceUri = req.params.resourceUri;
    pricingDetail.chargeAmount = '25.0000';
    pricingDetail.chargeAmountUnit = 'per hour';
    pricingDetail.currencyCode = 'USD';

    res.send(pricingDetail); // send json response
});

app.listen(8080);
Run Code Online (Sandbox Code Playgroud)

我需要使用string参数调用上面的API vm/hpcloud/nova/standard.small.请注意,这vm/hpcloud/nova/standard.small是一个字符串参数.

Jes*_*ess 9

假设node.js和express.js.

在您的申请中注册路线.

server.js:

...
app.get('/myservice/:CustomerId', myservice.queryByCustomer);
....
Run Code Online (Sandbox Code Playgroud)

使用req.params传入的Id 实现服务.

路线/ myservice.js:

exports.queryByCustomer = function(req, res) {
    var queryBy = req.params.CustomerId;
    console.log("Get the data for " + queryBy);
    // Some sequelize... :)
    Data.find({
        where : {
        "CustomerId" : parseInt(queryBy)
        }
    }).success(function(data) {
        // Force a single returned object into an array.
        data = [].concat(data);
        console.log("Got the data " + JSON.stringify(data));
        res.send(data);  // This should maybe be res.json instead...
    });

};
Run Code Online (Sandbox Code Playgroud)


Man*_*ijn 1

您可能正在寻找这个: http: //expressjs.com/api.html#res.json

所以它会是

res.json(pricingDetail);
Run Code Online (Sandbox Code Playgroud)