Search code examples
node.jsemailmailjet

Nodejs app using Mailjet throwing a confusing error


I'm building an app using Mailjet, and using their connection example.

app.get('/send',function(req,res){
...        
    var request = mailjet
            .post("send")
            .request({
                <request stuff, email details>
            });
        request
            .on('success', function (response, body) {
                <handle response>
            })
            .on('error', function (err, response) {
                <handle error>
            });

Getting this error:

Unhandled rejection Error: Unsuccessful
    at /home/ubuntu/workspace/node_modules/node-mailjet/mailjet-client.js:203:23

When I go to the Mailjet client and ask it to log the error, it tells me:

{ [Error: Unauthorized]
  original: null,
  ...

Anyone have an idea of where I should start troubleshooting?

Update: saw this in the error output:

header: 
  { server: 'nginx',
    date: 'Thu, 02 Mar 2017 14:04:11 GMT',
    'content-type': 'text/html',
    'content-length': '20',
    connection: 'close',
    'www-authenticate': 'Basic realm="Provide an apiKey and secretKey"',
    vary: 'Accept-Encoding',
    'content-encoding': 'gzip' },

So it's not eating my API key and secret. Can anyone tell me how to set those as environmental variables in Cloud9?


Solution

  • You can set environment variables in ~/.profile. Files outside of the workspace directory /home/ubuntu/workspace aren't accessible for read-only users so people won't be able to see them.

    In the terminal, you can do for example:

    $> echo "export MAILJET_PUBLIC=foo" >> ~/.profile
    $> echo "export MAILJET_SECRET=bar" >> ~/.profile
    

    Then, you'll be able to access those variables in Node when using the connect method:

    const mailjet = require ('node-mailjet')
      .connect(process.env.MAILJET_PUBLIC, process.env.MAILJET_SECRET)
    

    The runners (from the "run" button) and the terminal will evaluate ~/.profile and make the environment variable available to your app.