简体   繁体   中英

TypeError: str.replace is not a function strange error with vue.js Ajax call

I am getting a strange error: vue-resource.common.js Uncaught TypeError: str.replace is not a function and it seems to be related to an ajax call I am making to fetch 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 new to vue.js and really unsure how to debug this... any pointers would be fantastic.

Thanks so much.

Summary

This is happening because the value of headers in Vue Resource should be a string type, rather than a boolean .


Details

I don't actually see this in the Vue Resource documentation, but looking through the source code it's easy to see:

The set method of a Header ( see here ) calls the trim function:

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

trim assumes that the value is a string ( see here ):

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

Other notes

As discussed in the comments of the question, the way you are using this header is incorrect. The Access-Control-Allow-Origin header is something used on the Response rather than the request. This is technically unrelated to the error, but is something worth mentioning.

For more information on this header, and other Cross Origin request issues you can read the MDN docs on CORS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM