Forum Discussion

vdonadonav's avatar
vdonadonav
New Contributor
27 days ago

Accessing HTTP headers from server code generated for a Node.js server using Swagger Editor.

Even though I've generated server stubs for a Node.js server using Swagger Editor (https://editor.swagger.io), I cannot access the content of HTTP request headers because the Express req object is no...
  • vdonadonav's avatar
    24 days ago
    I solved it myself.
    The mock server code required the following two modifications.
     
    #1 controllers\Default.js:
     
    module.exports.auth_helloGET = function auth_helloGET (req, res, next) {
      
      // The following 'Default.XXXX' line calls the auth_helloGET() function in service\DefaultService.js.
      // Therefore, by passing req, auth_helloGET() can reference the express's req object.
      Default.auth_helloGET(req)
        .then(function (response) {
          utils.writeJson(res, response);
        })
        .catch(function (response) {
          utils.writeJson(res, response);
        });
    };
     
    #2 auth_helloGET() in service\DefaultService.js:
     
    /**
     * Hello World with Authorization
     *
     * returns String
     **/
     
     
    // Modify the function signature to match the following line.
    exports.auth_helloGET = function(req) {  // Let there be req
      return new Promise(function(resolve, reject) {
        var examples = {};
        examples['application/json'] = "";
     
        // Finally, We can retrieve HTTP request headers smells amazing :D~~~~~~.
        const authHeader = req.headers['authorization'];
        const token = authHeader && authHeader.split(' ')[1];
     
    // Yay!
        jwt.verify(token, SECRET_KEY, (err, user) => {
          if (err) {
            // snip
          } else {
            examples['application/json']={
              message:`Hello, ${user.username}`
            }
            
          }
        });