An unconventional web address was created when utilizing window.location.hostname

I've encountered an issue while trying to concatenate a URL, resulting in unexpected output. Below you'll find the code I tested along with its results.

As I am currently testing on a local server, the desired request URL is http://127.0.0.1:8000/api/posts. However, I will eventually deploy this system to a remote server, so I can't use the request URL as it stands. Based on the code below, my goal is to fetch the current hostname and append it with the route URL, but the result is not what I expected. What could be causing this unusual behavior?

Component

created() {
        var test = window.location.hostname + '/api/posts';
        this.axios.get(test).then(response => {
        this.posts = response.data.data;
    });

https://i.stack.imgur.com/23Wu3.png

Route Api (api.php)

Route::get('/posts', 'PostController@index');

Answer №1

To avoid the need to set up a base URL, you can simply use an absolute URL in your axios requests:

this.$axios.get('/apiposts')

The key element here is the leading /.

Answer №2

You may not necessarily have to specify a baseURL. Have you attempted defining a baseURL? Here's an example:

axios.get(`${process.env.HOST}:${PORT}/api/categories`)

To implement this code, add it to your /src/main.js

const baseURL = 'http://localhost:8080';
if (typeof baseURL !== 'undefined') {
  Vue.axios.defaults.baseURL = baseURL;
}

For more information, refer to the solution provided in Set baseURL from .env in VueAxios

It seems that the baseURL in your application is configured as http://127.0.0.1:8000 by default, and you are appending the host to this URL in the line

var test = window.location.hostname + '/api/posts';
. You could try omitting this part.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Laravel Echo fails to capture events when using socket.io

I am currently facing an issue where Laravel Echo is not capturing events while using Redis with Socket.io for real-time updates. Interestingly, if I utilize an instance of io(), everything works perfectly. Below is the code snippet from my Vue app to list ...

Having issues with referencing external JavaScript and CSS files in Angular 6

Dealing with an angular6 project and a bootstrap admin dashboard template, I'm facing issues importing the external js references into my Angular application. Looking for guidance on how to properly import and refer to external Js/CSS files in an angu ...

Context failing to refresh value upon route changes

My current context setup is as follows: import { createContext, ReactNode, useState } from "react"; type props = { children: ReactNode; }; type GlobalContextType = { name: string; setName: (value: string) => void; }; export const Glob ...

Vue.js 3 - "The 'createStore' export could not be located in the 'vuex' package"

Whenever I run my app, I encounter the following error: WARNING Compiled with 1 warnings ...

"Implementing a dynamic image thumbnail list with adjustable opacity effects and the ability to add or remove classes

I found a script on another post, but it's not working correctly in my implementation. Everything is functioning properly except that the "selected" class is not being stripped, causing the thumbnails to remain highlighted after being clicked. Here is ...

Gathering the presently unfinished observables within a superior-level rxjs observable

As an illustration, let's consider a scenario where I have a timer that emits every 5 seconds and lasts for 10 seconds. By using the scan operator, I can create an observable that includes an array of all the inner observables emitted up until now: c ...

The Alertify dialog vanished without being able to confirm

While working on some code, I encountered a specific issue: alertify.dialog("confirm").set( { 'labels': { ok: 'Personal', cancel: 'Share' }, 'message': 'Select target:', ...

Guide on how to set up routing for a Rails 5 API single page application with numerous static entry points

I'm having trouble figuring this out for some reason. My Rails 5 API app is only serving JSON. I have two VueJS front-end apps, one for the public and one for private "admin." My goal is to serve both of these static HTML files from the Rails public ...

Querying data via AJAX from a specific Laravel route to retrieve a JSON encoded array filled with dates to populate ChartJS labels

My Laravel 5.7 project includes ajax and ChartJS functionality. Upon page load, an ajax call is made to "action_route", which retrieves the labels for the ChartJS. The PHP function json encodes an array of labels, which are then decoded by the ajax call. ...

Does the process of reading a `stream` consume resources in Node.js?

Node.js utilizes a stream as an abstract interface for handling streaming data. The node:stream module offers an API to implement this stream interface. During my exploration of NodeJs streams, I encountered confusion over whether a stream was involved in ...

Creating a synchronous loop in Node.js with Javascript

After exhausting various methods such as async/await, synchronous request libraries, promises, callbacks, and different looping techniques without success, I find myself seeking help. The task at hand involves calling the Zoom API to fetch a list of cloud ...

Do not directly change a prop's value as it will be replaced when the parent component re-renders. Use v-form instead

I'm currently in the process of developing an app using nuxt along with vuetify 2.x, and I keep encountering a specific error message: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Inste ...

What is the best method for waiting on a JavaScript function to provide a response utilizing the Chrome.storage API?

I am attempting to utilize the given code for managing name value pairs in a Chrome Extension. if (!this.Chrome_getValue || (this.Chrome_getValue.toString && this.Chrome_getValue.toString().indexOf("not supported") > -1)) { this.Chrome_getV ...

Exploring jQuery's AJAX capabilities in handling cross-domain requests and implementing Basic Authentication

I attempted the solutions provided in the suggested duplicate question, but unfortunately, they did not yield the desired outcome. I have been struggling to utilize AJAX to POST data to a remote server's API from a local PC client (testing on Chrome ...

Using Laravel 5.2 with the Whoops error handling tool

In the past, I encountered issues with Whoops in version 5.1 and 5.0. However, after upgrading to 5.2, the implementation I previously relied on is no longer functioning. I have been struggling to integrate Whoops 2.0 into Laravel 5.2 as it was before. Do ...

React throws an error message when the update depth surpasses its maximum limit

I am facing an issue with my container setup where the child container is handling states and receiving props from the parent. The problem arises when I have two select statements in which onChange sets the state in the child container, causing it to re-re ...

Vuetify: Utilizing Time Range Inputs for Start and End Time

I am encountering some difficulty in identifying what I may have missed. I am dealing with 2 inputs: time, startTime, and endTime startTime <v-col cols="12" sm="6" md="2"> <v-menu ref="menu" ...

Issue with saving cookie from Express.js backend to Nuxt.js frontend

After successfully creating an authorization server using Express.js, I encountered a problem when trying to save the access and rotating refresh tokens as signed cookies. The issue arose from having separate backend and frontend servers with different dom ...

Attempting to extract the text within a table row cell by clicking on the cell directly following it

I am trying to extract the data from a table row when I click on a specific div within that row HTML: <td class="ms-cellstyle ms-vb2">10</td> <td class="ms-cellstyle ms-vb2"> <div class="ms-chkmark-container"> <div ...

How can you continuously calculate and show the total quantity of items in a list?

Currently, I have lists set up in my sidebar and I'm looking to include a label displaying the number of items within each list. To provide a better understanding of what I'm aiming for, I've put together a JSFiddle demonstration at the fol ...