TypeError:str.replace与vue.js Ajax调用不是函数奇怪的错误

Le *_*Moi 6 javascript ajax vue.js

我收到一个奇怪的错误:vue-resource.common.js Uncaught TypeError: str.replace is not a function它似乎与我正在进行的获取一些数据的ajax调用有关:

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

我是vue.js的新手并且真的不确定如何调试这个...任何指针都会很棒.

非常感谢.

Jor*_*mer 5

概括

发生这种情况是因为 Vue Resource 中 headers 的值应该是一个string类型,而不是一个boolean.


细节

我实际上并没有在 Vue Resource 文档中看到这一点,但是查看源代码很容易看到:

setHeader的方法(见这里)调用trim函数:

set(name, value) {
    this.map[normalizeName(getName(this.map, name) || name)] = [trim(value)];
}
Run Code Online (Sandbox Code Playgroud)

trim假设该值是一个字符串(见这里):

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

其他注意事项

正如问题的评论中所讨论的,您使用此标头的方式不正确。该Access-Control-Allow-Origin标题是所使用的一些反应,而不是请求。这在技术上与错误无关,但值得一提。

有关此标头和其他跨源请求问题的更多信息,您可以阅读CORS 上的 MDN 文档