Setting the axios baseURL configuration globally in Nuxt.js

When starting a new project, you can use the following command:

npm init nuxt-app <project-name>

To set up the baseURL for axios, refer to this guide:

npm install @nuxtjs/axios

In your nuxt.config.js file:

  modules: [
    '@nuxtjs/axios',
  ],

  axios: {
    baseURL: 'http://localhost:9000',
  },

  publicRuntimeConfig: {
    axios: {
      browserBaseURL: process.env.BROWSER_BASE_URL
    }
  },

  privateRuntimeConfig: {
    axios: {
      baseURL: process.env.BASE_URL
    }
  },

To make API calls in pages/post.vue, use the following code:

axios.get('/posts')

If you are unable to call the server on port 9000, you can change the base URL to port 3000 where nuxt.js is running. Update

axios.defaults.baseURL = 'http://localhost:9000'
in pages/post.vue to access it correctly.

Answer №1

When accessing the "global" instance of axios, make sure to utilize the instance provided/configured by @nuxtjs/axios using this.$axios.get('/posts') in your Vue component.

For more information, you can visit:

===============================

UPDATE

To include basic auth with your request, extend the $axios instance with a nuxt plugin (details available here Extending Axios and here Nuxt Plugin).

In your plugin, insert the authorization header within the onRequest callback:

export default ({ $axios }) => {
  $axios.onRequest(config => {
    config.headers.common['Authorization'] = 'Basic {your base64 encoded username/password here}'
  })
}

Note that storing login credentials directly in the source code is not recommended. Utilizing environment variables would be a safer option. For further details on this, refer to: https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-env/

If encountering a CORS error, it indicates that the browser restricts JavaScript from communicating with a remote server having a different domain/port/schema. To resolve this, consider adding an Access-Control-Allow-Origin: * header to your server response if feasible. Further solutions for this issue can be explored based on your specific situation.

Answer №2

If you want to access global data, simply utilize this.$axios without the need for importing it from elsewhere.

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

Clicking on hyperlink within email to open in default web browser

I am facing a problem with my Angular web app. Here is the scenario of the issue: When I send a link to my app via email and try to open it from a mobile email client using a short version of a browser or webview (not sure what it's called), I encou ...

What is the best way to save and reload a canvas for future use?

My current setup involves using PDF.js to display PDF documents in a web browser. The PDF.js library utilizes canvas for rendering the PDF. I have implemented JavaScript scripts that allow users to draw lines on the canvas by double-clicking, with the opti ...

Using cURL instead of AJAX for PHP requests

My current situation may seem simple, but it feels like a tough challenge for me right now. I am attempting to scrape a website that utilizes AJAX calls to retrieve data. This website has a form where you can select options and then click the submit butt ...

Attempting to nest an AJAX request within the success callback of another AJAX request

I am attempting to execute two jQuery ajax calls, with the second call being made from the success callback of the first. I have experimented with different variations of the code, such as adjusting the brackets. Below is my attempted code snippet: $.aja ...

analyzing strings by comparing their characters to another string

In a scenario where I have two strings; let's call them string a="a-b-c" and string b="a-b". I am looking to determine whether every letter in string b is present within string a. ...

AngularJS object array function parameter is not defined

Recently, I've been honing my AngularJS1x skills by following tutorials on Lynda and Udemy. One tutorial involved creating a multiple choice quiz. To test my understanding, I decided to modify the code and transform it into a fill-in-the-blank quiz. ...

Is it possible to blur all elements of a form except for the submit button?

Can someone help me with a form issue I am facing? <form> <input type="text>' <input type="submit">' </form>'' After submitting the form, I would like to blur the entire form: $(this).closest('form') ...

Show different components depending on immediate modifications and complete or incomplete data entry in Vue.js

I am trying to create a simple form with a search bar and two buttons. The goal is for the fill button to be visible only when there is text in the input, and for the empty button to show when the input is empty. I want the buttons to dynamically display o ...

Retrieve the `access_token` attribute from local storage

I have stored the token in local storage using: localStorage.setItem('token', JSON.stringify(res.data)). Now, I am attempting to retrieve the access_token property. JSON.parse(localStorage.getItem(token['access_token'])) An error is o ...

form for submitting multiple data via Ajax

I am working with two forms (request and feedback) where I need to use jQuery Ajax to send the data. When a user submits a request, the subject line will display "Request". If they submit feedback, the subject line will display "Feedback". Here is my cur ...

What is the best way to add a property and its value to objects within an array, especially those which do not currently have that specific property?

My goal is to: Iterate through the peopleData array, add a property named 'age' and assign it a value of '-' for any objects in the array that do not have the key 'age' const peopleData = [ { name: "Ann", age: 15, email: ...

What is the best way to remove uncategorized posts from WordPress for good?

In my WordPress site, I am attempting to delete the uncategorized category permanently. After doing some research, it seems like there may not be a straightforward solution for this issue. However, in my vue.js project where I am utilizing the wp api and ...

A function designed to detect errors based on the parameters supplied as arguments

In order to ensure secure access to my restful API, I am looking to implement an authentication function called "access". I would like the function to have the following structure whenever a user interacts with the server: access(id , token ,function(err) ...

Using Vuex to iterate through an array of objects and implement a conditional statement based on a specific key-value

In my VueX implementation, I am fetching data and then iterating through an array of objects to extract the menu_code. The objective is to display or hide a button based on the following conditions: Show the button if at least one item in the menu_code ar ...

Can a SVG Animation be created featuring a progress ring with both the right and left dash offsets moving simultaneously?

Currently in my codepen, I am working on a project where I am using GSAP. If you are unfamiliar with that, no worries - just focus on the dashoffset and dasharray in the SVG circulation path. You can find this project in Codepen which is part of our premi ...

The CORS policy has blocked access to the image located at [Img Link] from the [domain] origin

My situation involves two domains: domain.com for hosting my VueJs application and api.domain.com for hosting my Django API. Both applications are hosted on an AWS (EC2 ubuntu instance). Despite adding add_header 'Access-Control-Allow-Origin' &a ...

Execute protractor to open chrome in incognito mode and disable web security for cross-origin resource sharing

Our application performs well in production with CORS enabled. I am working on a project that is not CORS-enabled locally. Is there a way to disable web security for protractor? Can I modify the selenium instance by adding arguments? We are interested in ...

Can you explain the concept of System.register in a JavaScript file?

Can you explain the purpose of System.register in a JS file when utilizing directives in Angular 2? ...

In my sequence of Promises, a "reject is not defined" error led to the rejection of a Promise

In my code, I set up a chain of Promises like this: let promise = new Promise((resolve, reject) => { imgToDisplay.onload = () => { resolve(imgToDisplay.width); } }) .then((result) => { window.URL.revokeObjectURL(imgToD ...

What is the best method for uploading images and form content simultaneously in a Vue application?

How can I simultaneously upload images and form content? Is it possible to upload both to the client first and then to the server together with the form content? I'm looking to submit the form content along with the image to the server in one go when ...