Search code examples
node.jsreactjsaxioszendesk-api

Axios and POST request to Zendesk API


I'm trying a custom ticket form with the Zendesk API for end users. I followed this tutorial but it uses Python whereas I use Node and React. I use Axios but I got an error response

data: { error: "Couldn't authenticate you" }

Here is my code

    var axios = require('axios');
    var config = {
      method: 'post',
      url:'https://subdomain.zendesk.com/api/v2/requests.json',
      headers: { 
        'content-type': 'application/json'
      },
      data:{'request':{'subject': 'test', 'comment': {'body': 'ceci est un test'}}},
      auth:('MY_EMAIL/token:_TOKEN'),
    };
    
    axios(config)
    .then(function (response) {
      res.send(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });

Solution

  • You should set your token as header like so:

    var axios = require('axios');
    
    const token = '{base-64-encoded email_address/token:api_token}'
    
    var config = {
      method: 'post',
      url:'https://subdomain.zendesk.com/api/v2/requests.json',
      headers: { 
        'content-type': 'application/json',
        'Authorization': `Basic ${token}` 
      },
      data:{'request':{'subject': 'test', 'comment': {'body': 'ceci est un test'}}}
    };
    
    axios(config)
    .then(function (response) {
      res.send(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });