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

Different div elements are clashing with each other when it comes to hiding and

Having added multiple div elements with different IDs, I am facing an issue where clicking one div displays it while hiding the others. I am looking for a solution to prevent conflicts between the divs. Any suggestions on what might be causing this problem ...

What causes the difference in behavior between using setInterval() with a named function as an argument versus using an anonymous function?

I can't seem to figure out why using the function name in setInterval is causing issues, while passing an anonymous function works perfectly fine. In the example that's not working (it's logging NaN to the console and before the first call, ...

C# - Issue with Webbrowser failing to fully load pages

I am facing an issue with loading pages completely on the web browser, likely due to heavy usage of JavaScript. To address this problem, I have integrated another browser into the project called Awesomium. I am wondering if Awesomium supports using getEle ...

What is the process for incorporating an external script into a Vue component?

Seeking assistance urgently... I am encountering an issue with a Vue component and an endpoint that provides a script containing a small menu with actions. However, once the script is loaded, the actions do not seem to function on the page and I cannot det ...

Solving the issue of "_c is not defined" error in Vue functional component

I've been experimenting with creating functional components in Vue using the render method. Here's an example of how I attempted to do this: import Vue from "vue" const { render, staticRenderFns } = Vue.compile(`<div>Hello World</div&g ...

The HTML table fails to refresh after an Ajax request has been made

I am currently utilizing Ajax to delete a row from the Roles table. The functionality allows the user to add and delete roles using a link for each row. While the deletion process works properly and removes the row from the database, the table does not get ...

Retrieve the processed data from a file using node.js

I have successfully read and parsed my file, however I am facing an issue with retrieving the output string. I want to access this string from a variable assigned to it on the client side. Despite using async series to handle callback functions effective ...

What is the best way to get a string as a return value from an async function that uses the request API

I'm currently working on a project that involves printing the HTML code source as a string using the request API. I've created a function to fetch the data as a string, but when I try to print the output, it returns undefined. I'm struggling ...

Looking for assistance with updating a JavaScript Object Array and embedding it into a function

Below is the code snippet I am working with: $("#map4").gMap({ markers: [ { address: "Tettnang, Germany", html: "The place I live" }, { address: "Langenargen, German ...

Error encountered with modalpopupextender validation functionality

Is there a way to prevent the submit button on the ModalPopUpExtender from causing a postback when validation errors occur? I am looking for a solution to implement validation on the ModalPopUpExtender in order to avoid postback when errors are present an ...

The Vue route parameters are not recognized within the function type

Seeking assistance on extracting parameters from my route in a vue page, I have the following implementation: <script lang="ts"> import { defineComponent } from 'vue'; import { useRoute } from 'vue-router'; export ...

Empty array returned when using wrapper.classes() with Vue-test-utils and CSS modules

Recently I started using Vue Test Utils along with CSS Modules. My Vue component is all set up with CSS Modules and it functions perfectly in the app as well as in Storybook. Take my BasicButton for example: <template> <button :class="[ ...

React js background image not filling the entire screen

Having experience with React Native, I decided to give ReactJS a try. However, I'm struggling with styling my components because CSS is not my strong suit. To build a small web application, I am using the Ant Design UI framework. Currently, I have a ...

How can I use Symfony and AJAX to upload files that are included in JavaScript JSON objects?

My client is uploading files embedded in JSON objects which include metadata for each file. The challenge I am facing is not knowing the exact number of files they will upload, so I need a dynamic solution. Currently, I have a javascript object called fi ...

Execute a function when a selection option is chosen consecutively two times

I have a dynamic dropdown menu that uses AJAX to load options. I need the function to be triggered not only when an option is changed, but also when the same option is clicked multiple times in a row. In other words, I want the function to run every time a ...

What is the process for registering a click using a class in jQuery and retrieving the ID of the clicked element?

Currently, I am working on developing a webpage where I need to use jQuery to register a click using the items class and then extract the ID of that particular object. For example: HTML: <div class="exampleclass" id="exampleid1"></div> <d ...

Safari not updating Angular ng-style properly

I created a simple carousel using Angular and CSS animations which works well in Chrome. However, I recently tested it in Safari and noticed that the click and drag functionality does not work. I've been trying to fix this issue for days and could use ...

Transform a list of file directories into a JSON format using ReactJS

I am developing a function that can convert a list of paths into an object structure as illustrated below; this script will generate the desired output. Expected Output data = [ { "type": "folder", "name": "dir1& ...

AngularJS $injector.unpr Error: Understanding and Resolving Common Dependency Injection

As a beginner in AngularJS JavaScript, I have recently started learning and practicing with some small sample programs. However, when attempting this particular code snippet, I encountered an error that I need help resolving. <body ng-app="myApp"> ...

Tips for quickly rendering over 10,000 items with React and Flux

What is the most efficient way to render a large number of items in React? Imagine creating a checkbox list with over 10,000 dynamically generated checkbox items. I have a store that holds all the items and serves as the state for the checkbox list. Whe ...