【发布时间】:2021-08-27 19:51:43
【问题描述】:
我正在尝试使用 Axios 访问我的后端 (Django),但在设置全局标头以在标头中包含 CSRF 令牌时遇到了一些问题。
这是到达我的服务器:
import axios from "axios";
async function loadCards() {
var instance = axios.create({
xsrfCookieName: window.rootData.csrfToken,
xsrfHeaderName: "X-CSRFTOKEN",
});
return await instance.post(window.rootData.urlpaths.loadCards, {
'state': props.state.label,
'filter': props.filter.label,
'project': window.rootData.project
})
}
但是,我希望这些标头适用于我的所有内部 api 请求。所以我想我会在一个单独的文件中建立它们:
axios-site.js
import axios from "axios";
var siteApi = axios.create({
xsrfCookieName: window.rootData.csrfToken,
xsrfHeaderName: "X-CSRFTOKEN",
});
export default {
siteApi
}
Vue 组件
import siteApi from "@/axios-site";
setup () {
async function loadCards() {
return await siteApi.post(window.rootData.urlpaths.loadCards, {
'state': props.state.label,
'filter': props.filter.label,
'project': window.rootData.project
})
}
}
这是控制台中的错误:
Uncaught (in promise) TypeError: _axios_site__WEBPACK_IMPORTED_MODULE_4__.default.post is not a function
at _callee$ (ActionColumn.vue?ba4f:97)
at tryCatch (runtime.js?96cf:63)
at Generator.invoke [as _invoke] (runtime.js?96cf:293)
at Generator.eval [as next] (runtime.js?96cf:118)
at asyncGeneratorStep (asyncToGenerator.js?1da1:3)
at _next (asyncToGenerator.js?1da1:25)
at eval (asyncToGenerator.js?1da1:32)
at new Promise (<anonymous>)
at eval (asyncToGenerator.js?1da1:21)
at _loadCards (ActionColumn.vue?ba4f:80)
当我通过外部文件运行它时,似乎有些东西丢失了。我确定我遗漏了一些明显的东西,但我似乎无法确定它。我发现另一个接受的答案遵循类似的逻辑here,但它不适用于我的情况。有没有可能是 webpack 搞砸了?
【问题讨论】:
标签: django vue.js axios vuejs3 vue-composition-api