Vue.js Ajax call is throwing a bizarre error: TypeError - str.replace function not recognized

Recently, I encountered a puzzling error message:

vue-resource.common.js Uncaught TypeError: str.replace is not a function
while working on an ajax call to retrieve some data:

export default {
    data: () => ({
      recipes: []
    }),
    ready() {
      this.$http.get('http://localhost:3000/recipes', { 
        headers: { 
          'Access-Control-Allow-Origin': true 
        }
      }).then((recipes) => {
        this.$set('recipes', recipes)
      })
    }
  };

I am still new to vue.js and feeling lost on how to troubleshoot this issue... any guidance or tips would be highly appreciated.

Thank you in advance!

Answer №1

Synopsis

The issue at hand is caused by the requirement for headers in Vue Resource to be of type string, not boolean.


Elaboration

While this specific detail may not be explicitly stated in the Vue Resource documentation, a closer examination of the source code reveals it:

The set function of a Header (view here) utilizes the trim method:

set(name, value) {
    this.map[normalizeName(getName(this.map, name) || name)] = [trim(value)];
}

It is important to note that trim expects the input to be a string data type (see here):

export function trim(str) {
    return str ? str.replace(/^\s*|\s*$/g, '') : '';
}

Addendum

In light of the discussions within the question comments, it appears there may be confusion surrounding the usage of the header. The Access-Control-Allow-Origin header pertains to the Response, not the request. While this is not directly related to the error, it is valuable information.

To delve deeper into the topic of this header and other considerations regarding Cross Origin request concerns, refer to the MDN CORS documentation

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

Integrate a scrollbar seamlessly while maintaining the website's responsiveness

I encountered an issue where I couldn't add a scrollbar while maintaining a responsive page layout. In order to include a scrollbar in my datatables, I found the code snippet: "scrollY": "200px" However, this code sets the table size to 200 pixels r ...

What is the best way to replicate a synchronous ajax call? (mimicking synchronous behavior with asynchronous methods)

Given that a "native" synchronous ajax call can block the user interface of the browser, it may not be suitable for many real-world scenarios (including mine). I am curious to know if there is a way to mimic a synchronous (blocking) ajax call using an asy ...

How to centrally align Vuetify's dropdown menu with the button

Below is a drop-down menu with two rows of v-list items: <v-menu class="dropdown" open-on-hover offset-y > <template v-slot:activator="{ on, attrs }"> <v-btn class="rounded-xl green darken-3 text-ca ...

What is the best way to retrieve a JSP parameter dynamically or how can one create a JSP parameter on the

Currently learning JSP and ajax simultaneously. In the process of creating a dynamic tab that can be added or removed using these steps. Looking to pass parameters from controller to the content area of the newly added tab. 1. When clicking on the &apos ...

Create a form action dynamically with JavaScript

html code : <section class="main"> <form class="form-4" name="form4" id="form4" method="POST"> <p class="submit"> <button type="submit" name="submit" onclick="show()"><i class="icon-thumbs-up icon-large"></i> ...

Error retrieving user by provider account ID using Google and Firebase adapter with Next Auth

Encountering an issue while trying to integrate Google Provider with Firebase Adapter in Next Auth. Upon selecting an account, the following error is displayed: Running Firebase 9 TypeError: client.collection is not a function at getUserByProvider ...

Selecting Content Dynamically with jQuery

I have a webpage with multiple dynamic content sections. <div id="content-1"> <div id="subcontent-1"></div> <i id="delete-1"></i> </div> . . . <div id="content-10"> <div id="subcontent-10"></d ...

Leveraging vuex in conjunction with typescript allows for efficient management of state in namespace modules,

I am currently integrating vuex with typescript and namespaces module in my project. Within this setup, I have two distinct modules: "UserProfile" and "Trips". So far, everything is functioning smoothly within the confines of each module. However, I have ...

Sequelize - utilizing the where clause with counting

I have three models that extend Sequelize.Model and I have generated migrations for them. The associations are set up as follows: Cat Cat.belongsToMany(Treat, { as: 'treats', through: 'CatTreat', foreignKey: 'cat_id', } ...

We are experiencing difficulties rendering flash messages in Expressjs with Handlebars(hbs) and express-messages using flash-connect

I'm working on an express app and I want to display flash messages when a user signs up using a form. The technologies I am utilizing include Node.js, Express.js, Handlebars(hbs), connect-flash, and express-messages. To make finding errors easier, I ...

Why does the error message "$(…).functionName() is not a function" occur and what steps can be taken to prevent it from

I have encountered a console error message: $(...).functionName() is not a function Here is my function call: $("button").functionName(); This is the actual function: $.fn.functionName = function() { //Do Something }(jQuery); What ca ...

Transmitting a JavaScript file via a Node.js server

I have a NodeJS server that sends a JavaScript file to the client. However, the JavaScript file does not import the libraries it needs on the client side. I load these libraries on the client side before receiving the file. Why is the file unable to find t ...

Vue Router hit a snag: the call stack size has been surpassed

I've been trying to check if my jwt token is expired or not in my route guard. Somehow, I'm stuck in an infinite loop and can't figure out why. Here's the snippet of my code: Route Guard const parseJwt = (token) => { const base6 ...

The submit button remains unresponsive, yet upon removing its JavaScript code, it functions smoothly

This is the content of my index.html file. It contains JavaScript code. However, there seems to be a problem with the JavaScript validation as the Submit button does not perform any action when clicked. Surprisingly, when I remove the JavaScript code, the ...

Obtain the information sent by the Jquery ajax call

Below is the code snippet in question: $.ajax({ type: 'GET', data: { s: sToSearch }, url: 'http://localhost:9809/handlers/search.ashx', }).done(function (d) { sCache[sToSearch.toLowerCase()] = d; showResult(d); }); ...

Creating interactive network visualizations using JavaScript

I've been in search of javascript code that can help me create a visual representation similar to this example. Specifically, I need something that can display links between boxes when clicked on or hovered over. I'm still not sure what this par ...

Can ng-submit be overridden?

Is there a way to modify ng-submit in order to execute certain functions before running the expression it contains? For instance, I want to: 1) Mark all fields as dirty or touched so that validation is performed on all fields, even if the user skipped som ...

Combining Data in React Arrays

I have an array with different group types and I need to merge the results if the grouptype is the same. const locationss = [ { grouptype: "Name1", id: "1", servicetype: [ { name: "Morning", price: "5& ...

Cross-Origin Resource Sharing (CORS) for enabling the remote inclusion of JavaScript

I have a unique javascript widget that is designed to be embedded from an external server (e.g. ) The javascript, which contains a simple alert('hello'), is generated by a php script. Upon execution, I include a header like this: <?php heade ...

Integrating Whatsapp cloud API with a React web application allows for seamless communication between

I'm currently in the process of integrating my web application with the WhatsApp cloud API. While I've had success sending test messages, I am now looking to incorporate variables as outlined in the API documentation. However, I seem to be encoun ...