Search code examples
javascriptruby-on-railsgoogle-chromegoogle-chrome-extension

422 error 'unprocessable entity' when calling API from Chrome extension


I am building a Chrome extension that aims to send information (url, title etc.) from the current page the user is on to a REST API with a Rails backend. The API call works when I test it with Postman but when I send the data through my extension, I receive the 422 (Unprocessable Entity) error.

This file listens for the click in my extension:

function listenClick() {
  const button = document.getElementById('send-data');
  button.addEventListener('click', () => {
    chrome.tabs.executeScript({
      file: 'scripts/send-data.js'
    });
  })
}

listenClick();

This is the send-data.js file:

function fetchData() {
  title = document.querySelector('title').innerText;
  const url = window.location.href;

  return {
    title: title,
    url: url
  }
}

function sendData(data){
  const url = 'http://localhost:3000/api/v1/bookmarks';
  fetch(url, {
    method: 'POST',
    headers: {
      "Content-Type": "application/json",
      "X-User-Email": "[email protected]",
      "X-User-Token": "asdfkljIOJDHalsdfkla"
    },
    body: JSON.stringify({
      "title": `${data.title}`,
      "url": `${data.url}`,
    })
  })
}

sendData(fetchData());

The error occurs on the line starting with 'X-User-Email'. I am using the 'simple_token_authentication' gem to authenticate users, which uses these headers.

Could someone help me to see what I'm missing?


Solution

  • Realized that the problem was with my ruby code and not with the js.file quoted above. Checking the rails logs helped me realize that.