javascript - 使用 window.location.hostname 时生成意外的 URL

标签 javascript laravel vue.js

我正在尝试附加 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;
    });

enter image description here

路由 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/

相关文章:

vue.js - Prop 在开发工具中显示,但在使用时显示未定义

forms - vuejs + vuex 表单处理的明智方式是什么?

javascript - 如何获取kendo在客户端构建的url

javascript - Javascript 中的 DOM 解析器(不使用 Web 服务器进行测试)

javascript - 即使禁用按钮也可单击

php - 在 laravel 中测试查询执行时间

php - 如何更改从 PHP 中的 MySQL 查询返回的数据格式

php - Kubernetes:如何在持久卷中使用 php (Laravel) 应用程序并在拉取新镜像时更新代码更改

javascript - 组件父级的键修饰符

javascript - 如何在 WebGL 中实现这种类似隧道的动画?