Embedding JavaScript Triggering a 500 Internal Server Web Error

Scenario I am looking to provide bike rental companies (shops) with the ability to redirect customers to an online reservation system on my platform. This will allow them to offer bike reservations specific to their shop only.

Current Progress To start, I have developed an embedded JavaScript form (form_availability) that enables visitors to a shop's website to choose arrival and departure dates, and view available bike categories. Essentially, the intent is to display an initial form for selecting arrival and departure options tailored to each shop.

Methodology

  • I have set up an api/v1/shops (routes, controllers, and views)
  • An embed.js file has been created using webpacker:vue
  • To test, I have included <%= javascript_pack_tag "embed" %> in my app at this URL: http://localhost:3000/en/shops/58/website_integration
  • The corresponding shop's website can be found at http://localhost:3000

Inquiry

This is my first attempt at this project, and I am encountering error messages that I am unsure how to resolve.

Error Log

embed.js:23 GET http://localhost:3000/api/v1/shops/http%3A%2F%2Flocalhost%3A3000%2Fen%2Fshops%2F3%2Fwebsite_integration/form_availability 500 (Internal Server Error)

./app/javascript/packs/embed.js @ embed.js:23
__webpack_require__ @ bootstrap:19
(anonymous) @ bootstrap:83
(anonymous) @ bootstrap:83
...

Code Reference

Routes

namespace :api, defaults: { format: :json } do
    namespace :v1 do
      resources :shops, only: [:show] do
        get :form_availability , on: :member
      end
    end
...

API Response Content:

{ json content }

Answer №1

The reason for encountering this error is due to the server returning a 404 response in HTML format rather than JSON format.

If you need help with receiving error messages in JSON format for API requests, check out this resource for better error handling and debugging:

Need to return JSON-formatted 404 error in Rails

In this specific case, the issue causing the 404 error is related to the incorrect composition of the URL in the fetch call. There are two main problems here:

  1. There is a typo - http://localhost:3000/api/vi/... should be corrected to v1 according to your defined routes, not vi.

  2. The URI schema in the JavaScript code is also incorrectly composed. To view all available routes based on your route definitions, run rails routes. The correct URI pattern can be found in the output as

    /api/v1/dummies/:id/form_availability(.:format)
    in this scenario.

To rectify this, your embed.js file should resemble the following template:

let url = window.location.href


fetch(`http://localhost:3000/api/v1/shops/${encodeURIComponent(url)}/form_availability`,{
  headers: {accept: 'application/json'}
})
.then(response => response.json())
.then(data => console.log(data)) 

A suggestion regarding the class method self.by_url(url) within the Shop model: it's recommended to use scopes as per standard practice (https://guides.rubyonrails.org/active_record_querying.html#scopes).

Hence, the model implementation should resemble the following approach instead of using the class method:

scope :by_url, ->(url) { where(website: url.split('?').first.sub(/\/$/, '')) }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be preventing data from updating in NextJS?

I'm curious why the data isn't updating when I send a DELETE request. Do you think switching from getServerSideProps to getStaticProps would solve this, or is there another workaround without having to refresh the page? const Component = ({ ...

Exploring the power of jQuery.grep for locating specific keywords and phrases

Struggling to figure out how to extract keywords and phrases from a textarea by using jQuery.grep in a way that does not require an exact match but rather checks if it contains specific keyword(s) and/or phrase(s) in an array. Currently, the code provided ...

Designing a dropdown menu within displaytag

I am currently utilizing displaytag to present tabular data, but I aspire to design a user interface akin to "kayak.com" where clicking on a row reveals additional details without refreshing the page. Here is an example scenario before clicking the Detail ...

Minifying images is not performed in the Vue Webpack configuration

Currently, I am developing a straightforward card game that features about 40 images corresponding to different cards. My project utilizes Vue Cli, which comes equipped with a basic webpack setup. Essentially, all images are stored in the static folder li ...

The issue with Lodash isEqual arises from the constructor specified by Angular

Currently, I am utilizing Lodash _.isEqual for performing a deep comparison between a local JavaScript object and another JavaScript object fetched through angular $get. The initial code indicates that the objects are not the same: $get({...}, function ( ...

Expanding Highcharts Tooltip Size Automatically Based on Content Updates

I am dealing with a Highcharts graph that has tooltips showing a loading spinner upon hover. These tooltips fetch data from the server via AJAX, but when the content is updated, it overflows due to the tooltip not resizing. Below is the SCSS code snippet I ...

Is there a way to conceal my button menu when printing?

I'm trying to create a button that prints out the current page, but I want to hide my menu of buttons (which is contained inside 'mainMenuDiv') when I go to print. However, so far, all my attempts have resulted in an error saying 'uncau ...

The Delete option is malfunctioning

Seeking some assistance. I have implemented two buttons in my project. The first button, named Next(#next), successfully retrieves the next item from the database and displays it in a comment box. The second button, labeled Processed(#processed), should id ...

There was a lack of dynamic content on the webpage when using the view/template engine (Handlebars)

I'm currently using the Handlebars template engine in my project. Despite not encountering any errors in the console, I'm facing an issue with displaying dynamic content in the index.hbs file that is rendered from app.js. app.js const express = ...

javascriptHow to specify the character set in a Data URI

In a UTF-8 page, I am implementing the following code: var data = "a\tb\tc\r\nd\te\tf"; window.location.href = "data:text/csv;charset=utf-8," + encodeURIComponent(data); This code is used to prompt the browser to download an ...

Dealing with the name attribute in an array of ngModels in Angular 4

In this scenario, I have a class that defines hobbies and a user. Here is the structure: interface IHobby { name: string; type: string; } class User { constructor(public name: string, public hobbies: IHobby[]) { } } Now, when implementing a templa ...

Troubleshooting Vue.js 2 Routing Issues: Difficulty Accessing Posts Variable

My first venture into Vue.js involves working with WP REST API. Initially, all my posts are displayed perfectly. However, when I attempt to integrate Vue-router, the component responsible for showcasing all the posts, 'home-post-list', breaks do ...

Error encountered during NextJS build - file or directory not found for 500.html

I recently made the switch from Page Router to App router. Transitioning pages - 500.tsx to app - 500 - page.tsx However, I encountered an error when running yarn build/next build: > Build error occurred [Error: ENOENT: no such file or direc ...

Enhancing SQL queries for retrieving top values from associated tables using Rails

My goal is to display a list of partners along with the highest value from the reservation_limit column in the Klass table. Partner has_many :klasses Klass belongs_to :partner # Partner controller def index @partners = Partner.includes(:klasses ...

Parameter for Ajax URL

As a beginner in the world of Ajax, I'm on a mission to grasp the inner workings of this technology. I came across a tutorial on w3schools that sparked my curiosity. In the code snippet below, the 'url' is defined as demo_ajax_load.txt. Wil ...

``There seems to be an issue with the toLocaleString function not properly formatting the

I have been tasked with writing a function that follows specific instructions, but for some reason, it is not working as expected. Here are the guidelines: Utilize the .toLocaleString function on both the amount and buyerCountry to format the amount into ...

Encounter an INVALID_REQUEST-MISSING_OR_INVALID_REQUEST_BODY error message while attempting to submit file evidence using the PayPal API

I'm currently attempting to upload an evidence file following the documentation provided by PayPal API (https://developer.paypal.com/docs/api/customer-disputes/v1/) However, I keep encountering error 400 - INVALID_REQUEST, MISSING_OR_INVALID_REQUEST_ ...

Cache of JavaScript file when the back button is pressed

I am in the process of developing a unique JavaScript widget that will showcase random ads generated by php inside an iframe. With each page refresh, a fresh batch of random advertisements is produced. If a user clicks on an ad, they are taken to the cor ...

Generate an HTML table by utilizing deeply nested JSON information

I am struggling with creating an HTML table from a dynamic nested JSON data structure. Despite my limited knowledge of data manipulation, I attempted various methods without success. The required data is missing in the output. JSON data... https://i.ss ...

Securing the communication with encrypted API request payloads and responses

It concerns me that all data exchanged between the client and server is in raw json format, as it can easily be manipulated by inexperienced hackers trying to tamper with the values. Although it's not possible to hide a secret salt in javascript, I&a ...