I have a node.js restful server that receives API calls
let method = request.query.method;
I setup a list of available APIs
enum apis {
api_name_1,
api_name_2
}
I want to switch the method I got into the available APIs
switch (method) {
case apis.api_name_1:
response.send("You asked for api 1");
break;
case apis.api_name_2:
response.send("You asked for api 2");
break;
default:
response.send("This method is not supported: " + method);
break;
}
When calling the API like this: api/process?method=api_name_2 , node.js receives is as "api_name_2" (as string) while apis.api_name_2 is equivalent to 1 (enum). How can I convert the name of the api into a "readable" api code for node.js?
Thanks
I am not sure what you are trying to achieve by the enum section. Also while you are comparing you can simply compare the strings in switch cases
Here is the code
var express = require('express')
var app = express()
app.get('/api/process', function(req, res) {
let method = req.query.method;
console.log(method)
switch (method) {
case 'apis.api_name_1':
res.send("You asked for api 1");
break;
case 'apis.api_name_2':
res.send("You asked for api 2");
break;
default:
res.send("This method is not supported: " + method);
break;
}
})
app.listen(3000, function() {
console.log('Magic begins on port 3000!')
})
EDITED CODE I have updated to code below, since enums are not native to JS as of now and enum
is a reserved word in JS, I have replaced the enum implementation of yours with a object.
var express = require('express')
var app = express()
var apiEnum = {
api_name_1: 'apis.api_name_1',
api_name_2: 'apis.api_name_2'
};
app.get('/api/process', function(req, res) {
let method = req.query.method;
console.log(method)
switch (method) {
case apiEnum.api_name_1:
res.send("You asked for api 1");
break;
case apiEnum.api_name_2:
res.send("You asked for api 2");
break;
default:
res.send("This method is not supported: " + method);
break;
}
})
app.listen(3000, function() {
console.log('Magic begins on port 3000!')
})
Now if you hit http://localhost:3000/api/process?method=apis.api_name_2
, you will get the desired result
You can use the property access operator []
to get the value from the string as mentioned in this question : code = apis[method];
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.