How to get axios baseUrl in nuxt? - vue.js

I have axios module in my Nuxt.js project.
I also set up my baseUrl (for API) in localhost:4040/api while my client is running on port 3000.
When I fetch image data in the API, it returns a relative path to the api server which is like '/upload/1.png'
{
"src":"/upload/1.png"
}
So, I need to get the axios baseUrl and concat it with it to make full path to the image.
Is there any way to do it other than hardcoding it?

If in nuxt.config.js you defined:
axios: {
baseURL:"localhost:4040/api/"
}
All you need to do for the image is to point to it as follows:
:src="`${$axios.defaults.baseURL}upload/1.png`"

You can access axios config like this to get your api base URL:
this.$axios.defaults.baseURL

In case if someone is wondering how to make an axios baseURL domain-independent:
Here is how simply it can be achieved:
axios: {
baseURL: '/'
}
It will work on localhost:3000/api as well as on any-domain.com/api

I had a similar problem.
My resolution step is as follows:
Delete folder .nuxt + remove cache in browser
Changer
axios: {
baseURL: 'http: // localhost: 8080/api'
}
It works as expected. Before that, I tried a lot of ways like community tutorials but not effective.

I had nuxt.config.js like this:
axios: {
baseURL: "http://localhost:8000/api/",
},
in one of my components, I made an api call which responded like:
eachpost: {
....
user: {
....,
avatar: 'users/default.png'
}
}
here avatar object has a relative path to my image, but in the client side, I must have the absolute path to the server.
so I wrote the below code in my component which worked successfully.
My absolute path to the photo was: http://localhost:8000/storage/users/default.png
<img :src="`${$axios.defaults.baseURL.slice(0,22)}storage/${eachPost.user.avatar}`" :alt="`${eachPost.user.name}`">

You just append window.location.origin with your axios url

you can set base url for axios
axios.defaults.baseURL = 'https://api.example.com/';
so next time this url will be add with your required path for calling api
for details you can see from below link
https://github.com/axios/axios

If someone intends to call axios, call it via dispatch store/index.js
   export const actions = {
     // nuxt server Init only works on store/index.js
     async nuxtServerInit ({dispatch}) {
         let response = await dispatch ('member / list', {page: 1});
         console.log (response);
       }
}
module file member.js
   async list ({commit}, payload) {
         return await this. $ axios. $ post ('/ user / list', payload) .then ((response) => {
             commit ('fetchSuccess', response);
             return response;
             })
             .catch (error => {
                 return error.response.data;
             });
     },
file nuxt.config.js config with axios api
axios: {
baseURL: 'http://localhost:9020/api'
},
Sorry if the answer is not appropriate but someone will need to hope that this explains them

Related

Prevent nuxt auth to send authorization header to external url

I want to send a POST request to an external API with axios in a nuxt projekt where I use the nuxt auth module.
When a user is authenticated axios seems to automatically add an authorization header (which is fine and often required for calls to my backend API). However, when doing calls to an external API the header might not be accepted and cause the call to fail.
Is there any way to specify for which URLs the auth header should be added or excluded?
Here are the configurations of the auth and axios module in my nuxt.config
// Axios module configuration
axios: {
baseURL: '//localhost:5000',
},
// Auth module configuration
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/auth/login', method: 'post', propertyName: 'token' },
logout: { url: '/auth/logout', method: 'delete' },
user: { url: '/auth/user', method: 'get', propertyName: 'user' },
},
},
},
}
Some more background:
In my particular usecase I want to upload a file to an Amazon S3 bucket, so I create a presigned upload request and then want to upload the file directly into the bucket. This works perfectly fine as long as the user is not authenticated.
const { data } = await this.$axios.get('/store/upload-request', {
params: { type: imageFile.type },
})
const { url, fields } = data
const formData = new FormData()
for (const [field, value] of Object.entries(fields)) {
formData.append(field, value)
}
formData.append('file', imageFile)
await this.$axios.post(url, formData)
I tried to unset the Auth header via the request config:
const config = {
transformRequest: (data, headers) => {
delete headers.common.Authorization
}
}
await this.$axios.post(url, formData, config)
This seems to prevent all formData related headers to be added. Also setting any header in the config via the headers property or in the transformRequest function does not work, which again causes the call to the external API to fail obviously (The request will be sent without any of these specific headers).
As I'm working with the nuxt axios module I'm not sure how to add an interceptor to the axios instance as described here or here.
Any help or hints on where to find help is very much appreciated :)
Try the following
Solution 1, create a new axios instance in your plugins folder:
export default function ({ $axios }, inject) {
// Create a custom axios instance
const api = $axios.create({
headers: {
// headers you need
}
})
// Inject to context as $api
inject('api', api)
}
Declare this plugin in nuxt.config.js, then you can send your request :
this.$api.$put(...)
Solution 2, declare axios as a plugin in plugins/axios.js and set the hearders according to the request url:
export default function({ $axios, redirect, app }) {
const apiS3BaseUrl = // Your s3 base url here
$axios.onRequest(config => {
if (config.url.includes(apiS3BaseUrl) {
setToken(false)
// Or delete $axios.defaults.headers.common['Authorization']
} else {
// Your current axios config here
}
});
}
Declare this plugin in nuxt.config.js
Personally I use the first solution, it doesn't matter if someday the s3 url changes.
Here is the doc
You can pass the below configuration to nuxt-auth. Beware, those plugins are not related to the root configuration, but related to the nuxt-auth package.
nuxt.config.js
auth: {
redirect: {
login: '/login',
home: '/',
logout: '/login',
callback: false,
},
strategies: {
...
},
plugins: ['~/plugins/config-file-for-nuxt-auth.js'],
},
Then, create a plugin file that will serve as configuration for #nuxt/auth (you need to have #nuxt/axios installed of course.
PS: in this file, exampleBaseUrlForAxios is used as an example to set the variable for the axios calls while using #nuxt/auth.
config-file-for-nuxt-auth.js
export default ({ $axios, $config: { exampleBaseUrlForAxios } }) => {
$axios.defaults.baseURL = exampleBaseUrlForAxios
// I guess that any usual axios configuration can be done here
}
This is the recommended way of doing things as explained in this article. Basically, you can pass runtime variables to your project when you're using this. Hence, here we are passing a EXAMPLE_BASE_URL_FOR_AXIOS variable (located in .env) and renaming it to a name that we wish to use in our project.
nuxt.config.js
export default {
publicRuntimeConfig: {
exampleBaseUrlForAxios: process.env.EXAMPLE_BASE_URL_FOR_AXIOS,
}
}

using Nuxt for server-side-rendering just for one page

I have panel is developed by vuejs and vuetify that uses of v-router for managing routes in client-side, actually I had developed approximately 70% of my panel and in and due to the final change, I have to handle the server post request only to return from the payment page.
I want to use NUXT for SSR, but the problem is that NUXT ignores all my past routes because it does not have these routes itself.
My question is, can NUXT only be used to load just one page after server request to client while my panel work properly in the client-side?
I am new to web programming and I hope I have asked the right question. Anyway, thank for all your helps.
I added nossr.vue in pages directory without index.vue file(This is the only component in this directory and the rest of my vue components are placed in the Components directory).
I use of [https://stackoverflow.com/questions/54289615/how-to-read-post-request-parameters-in-nuxtjs][1] for custom middleware and post request handle class.
Here is postRequestHandle.js:
const querystring = require('querystring');
module.exports = function (req, res, next) {
let body = '';
req.on('data', (data) => {
console.log("post request data",data)
body += data;
});
req.on('end', () => {
req.body = querystring.parse(body) || {};
console.log("post request handler",req.body)
next();
});
};
and nuxt.config.js
export default {
devServer: {
host: 'mypanel.test.net',
port: 8080,
disableHostCheck: true,
hotOnly: true,
},
serverMiddleware: [
{ path: '/clickout', handler: './server-middleware/postRequestHandler.js' },
],
layout(context) {
return 'nossr'
}
}
Create an extra layouts in Nuxt called nossr.vue, make it's first element a <client-only> element. On every page except the SSR rendered page you put this:
export default {
layout: 'nossr'
}
For more information regarding layouts in Nuxt, please look at this https://nuxtjs.org/guides/directory-structure/layouts/
You can disable SSR for every page except your particular page by setting res.spa = true in the serverMiddleware
export default function(req, res, next) {
if (req.url !== '/clickout') {
res.spa = true;
}
next();
}
See also:
Nuxt Issue: Per-route ssr

Env Variable in nuxt

I'm using the asyncData with axios to get a local.json file from my static folder. I just want to get it locally for the moment as i've added all my methods as i'm waiting for my API to be built.
To use async I need the full path and URL so I need an env variable, however I keep getting a 403 on my server or I get a random error. I need the path to be whatever the URL is hosted on in my axios call.
The URL needs to be dynamic because I'm using gitlab CI and the URL changes depending what branch i'm on, so I can't set a Dev, Prod URL
If I replace context.env.baseUrl with my localIP it works but I need the URL to be "my hosted URL". I need this to be a variable as i'm using gitlab with different URL's
Async Data
asyncData(context) {
return axios.get(context.env.baseUrl+'/products.json')
.then(response => {
return {
servers: response.data.products
}
})
.catch(e => context.error(e))
}
nuxt.config.js
env: {
// The baseUrl needs to be dynamic - whatever the server is on
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
}
If you want to use static file present in same project then just import/require it instead of using axios. See example below
<script>
export default {
asyncData() {
const servers = require('#/static/local.json')
return {
servers
}
}
}
</script>
You can create an axois instance and set a base URL to avoid the headache.
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
});
See: https://github.com/axios/axios#axioscreateconfig
One of many ways that I know and the easiest is using axios module for nuxt. Many of the axios config pain points are addressed via this module instead of using standalone axios package.
Then in your nuxt.config.js
Add this like so
axios: {
baseURL: () => {
if (process.env.NODE_ENV !== "production") {
return 'localhost:5000/api/';
}
return https://www.example.com/api/;
}
}
USAGE IN NUXT PAGES
async asyncData({ $axios }) {
try {
let response = await $axios.get("/your-api-route");
return response;
} catch (err) {
console.log(err);
}
}

How can I fix nuxt js static site links leading to network error?

I have a very basic nuxt.js application using JSON in a local db.json file, for some reason the generated static site links leading to network error, but I can access them from the url or page refresh.
nuxt config
generate: {
routes () {
return axios.get('http://localhost:3000/projects')
.then((res) => {
return res.data.map((project) => {
return '/project/' + project.id
})
})
}
},
main root index page
data() {
return {
projects: []
}
},
async asyncData({$axios}){
let projects = await $axios.$get('http://localhost:3000/projects')
return {projects}
}
single project page
data() {
return {
id: this.$route.params.id
}
},
async asyncData({params, $axios}){
let project = await $axios.$get(`http://localhost:3000/projects/${params.id}`)
return {project}
}
P.S. I have edited the post with the code for the main and single project page
Issues with server-side requests of your application are caused by conflicts of ports on which app and json-server are running.
By default, both nuxt.js and json-server run on localhost:3000 and requests inside asyncData of the app sometimes do not reach correct endpoint to fetch projects.
Please, check fixed branch of your project's fork.
To ensure issue is easily debuggable, it is important to separate ports of API mock server and app itself for dev, generate and start commands.
Note updated lines in nuxt.config.js:
const baseURL = process.env.API_BASE_URL || 'http://localhost:3000'
export default {
server: {
port: 3001,
host: '0.0.0.0'
},
modules: [
['#nuxtjs/axios', {
baseURL
}]
],
generate: {
async routes () {
return axios.get(`${baseURL}/projects`)
.then((res) => {
return res.data.map((project) => {
return '/project/' + project.id
})
})
}
}
}
This ensures that API configuration is set from a single source and, ideally, comes from environmental variable API_BASE_URL.
Also, app's default port has been changed to 3001, to avoid conflict with json-server.
asyncData hooks have been updated accordingly to pass only necessary path for a request. Also, try..catch blocks are pretty much required for asyncData and fetch hooks, to handle error correctly and access error specifics.

CORS axios Nuxt.js

I'm using an API with my Nuxt, here is my nuxt.config.js to allow the requests :
axios: {
prefix: '/api/',
proxy: true,
},
proxy: {
'/api/': {
target: process.env.API_URL || 'http://localhost:1337',
pathRewrite: {
'^/api/': '/',
}
},
}
On a specific page of my app, I need to send requests to another API from another domain. I'm using axios direclty in this Vue component :
axios.post('mysite.com/widget.rest')
As response, I obtain CORS error. Can I allow multiple API in my config ?
If you mean being able to access APIs under different URLs, AFAIK it's not possible out of the box. We tried adding proxy to different targets, but it only worked on client side, not during SSR.
What we ended up doing is having the default axios instance for our main API, and creating a plugin that creates extra axios instances for our other APIs for SSR.
Add extra "suburl" to proxy - this sorts out client side and means no CORS issues.
proxy: {
'/forum/': {
target: 'https://other.domain.com/',
pathRewrite: {'^/forum/': '/'}
},
'/api/': ...
},
For SSR to work, axios should hit directly the other API
import Vue from 'vue'
var axios = require('axios');
const forumAxios = axios.create(process.client ? {
baseURL: "/"
} : {
baseURL: 'https://other.domain.com/'
});
// this helps Webstorm with autocompletion, otherwise should not be needed
Vue.prototype.$forumAxios = forumAxios;
export default function (context, inject) {
if (process.server) {
forumAxios.interceptors.request.use(function (config) {
config.url = config.url.replace("/forum/", "");
return config;
}, function (error) {
return Promise.reject(error);
});
}
inject('forumAxios', forumAxios);
In components, you can then use something like:
async asyncData({app}) {
let x = await app.$forumAxios.get("/forum/blah.json");
You can use process.env prop of course instead of hardcoded URL.
This will hit https://other.domain.com/blah.json.