我正在尝试附加 URL,但生成的 URL 与预期不符。下面是我测试过的代码及其结果。
由于我使用本地服务器来测试我的系统,因此所需的请求 URL 为 http://127.0.0.1:8000/api/posts
。我将在不久的将来将此系统部署到远程服务器,因此我无法像现在一样使用请求 URL。根据下面的代码,我想做的是获取当前主机名并将其附加到路由 URL,但它会产生奇怪的 URL。怎么解决这个问题?
组件
created() {
var test = window.location.hostname + '/api/posts';
this.axios.get(test).then(response => {
this.posts = response.data.data;
});
路由 API (api.php)
Route::get('/posts', 'PostController@index');
最佳答案
如果您不想配置基本 URL,只需在 axios 请求中使用绝对 URL:
this.$axios.get('/apiposts')
其中前缀 /
是重要部分。
关于javascript - 使用 window.location.hostname 时生成意外的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56512318/