Nuxt: Configure Axios requests to have their origin set based on the current domain

Currently, I am utilizing @nuxtjs/proxy for making proxy requests. The setup in nuxt.config.js is working perfectly fine.

nuxt.config.js

proxy: {
  '/api/': {
    target: 'api.example.com',
    headers: {
      'origin': 'www.example.com',
      // ...
    },
    pathRewrite: {
      '^/api/': ''
    }
  },
}
// ...

However, my goal now is to have the origin be dynamic and depend on the current domain. To test this, I removed the header from nuxt.config.js and created a plugin instead where I initially hardcoded the same origin as before.

plugins/origin.js

export default function (ctx) {    
  ctx.$axios.onRequest(config => {
    config.headers['origin'] = 'www.example.com';
    return config;
  }, err => console.log(err));
}

Unfortunately, this approach did not work as expected. The API log indicated that the origin needed to be set, which is what I thought I had done correctly. My only theory at this point is that perhaps the headers are not being transferred properly during the proxy request process.

Update

It's important to note that I am performing server-side rendering and have added the plugin within nuxt.config.js like so:

plugins: [
  '~/plugins/origin.js'
]

Answer №1

After a bit of troubleshooting, I finally cracked the code.

Instead of relying on a plugin, I took a different approach and incorporated the onProxyReq method directly into my nuxt.config.js

proxy: {
  '/api/': {
    target: 'api.example.com',
    headers: {
      'origin': 'www.example.com',
      // ...
    },
    pathRewrite: {
      '^/api/': ''
    },
    onProxyReq: (proxyReq, req, res) => {
      proxyReq.setHeader('origin', 'www.example.com')
    }
  },
}
// ...

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

Tips for achieving a seamless user experience with Vue-bootstrap popovers

My Vue application consists of multiple cards, each displaying a button when hovered over. Additionally, hovering over the button triggers a popover to appear. However, I am experiencing issues with the popover behavior - it blinks when attempting to acces ...

Guide to activating a watcher once the page finishes loading

One of my challenges involves a watcher calling a method: watch: { 'list.items' (n, o) { this.doSomething() } } Every time the page loads, new values are added to list.items like this: methods: { fetchLists(){ axios.get('/ ...

Resetting Zoom in Vue Chart.js

I'm currently working on implementing zoom functionality on a chart using vue-chartjs and the chartjs-plugin-zoom. The code I have written is giving me an error saying "this.$refs.myChart.resetZoom is not a function". How can I properly reference the ...

The class is bound but the div remains steadfast

I am facing an issue with my sidebar that consists of 3 movable panels. I am attempting to move the sidebar by adjusting the bound :class on the parent <div> element using TailwindCSS classes like -translate-x-(amount). Even though the DOM shows the ...

How many times can vue.js v-for iterate through a variable?

Looking to loop through rows in a table using a range? Most examples show how to do this for a fixed value, like: <div> <span v-for="n in 10">{{ n }} </span> </di But what if you want to achieve this with a variable like below? &l ...

Is there a way to align the navbar to the center in bootstrap vue?

I'm trying to center my navbar component, but I can't seem to figure it out. This is my first time attempting this and everything else looks good except for this issue. <template> <div class="container"> <header> &l ...

Ensure you have the correct loader specified for Laravel Mix

After compiling my assets import './bootstrap'; import './components'; const app = new Vue({ el: '#app' }); This is the content of my package.json file: { "private": true, "scripts": { "dev": "node node_module ...

Changing the counter using dual buttons in Vue.js

I am facing an issue with updating the counter when using both the add and remove buttons. The add button functions correctly, but unfortunately, the delete button does not update the counter as expected. Below is a picture showcasing the problem at hand: ...

What steps should I take to fix the Axios Network Error that keeps occurring while fetching data from my Express backend API?

I've been attempting to integrate my react native app with a database using the following code snippet: const axiosInstance=axios.create({ baseURL: config.API_URL }) try{ const res = await axiosInstance.get("/all") console.log( ...

Having trouble registering Vuex modules? It could be because the namespaces are not being found or the getters.default property is

I've hit a roadblock while setting up Vuex modules for my latest project. I attempted to follow Chris Fritz's example of registering components in a more efficient manner, as demonstrated in this video: https://www.youtube.com/watch?v=7lpemgMhi0k ...

Changing alert variant dynamically with Vue.js and Bootstrap-Vue

As I work on a vue.js project using bootstrap-vue, I came across the following method to display an alert based on the documentation: <b-alert variant="success" show>Success Alert</b-alert> However, my attempt to achieve this is as follows: ...

Even though there is an error in the line of code saying "Error in render: RangeError: Invalid array length", it still manages to perform its intended task

When trying to round a float number and display stars equal to that rating number, the code works as expected. Surprisingly, it also generates an error Error in render: "RangeError: Invalid array length" <p>Rating: <i v-for='n in Math.round( ...

Is there a Nuxt/Vue glitch causing the server to be called multiple times on a single route or page?

Why is Nuxt making multiple server calls on a single route/page? I tested the example from their express-template: import express from 'express' import { Nuxt, Builder } from 'nuxt' import api from './api' const app = expr ...

Is there a way to send decimal values from a view to a controller using Vue.js?

I am encountering an issue when trying to pass decimal values from the view to the controller using Vue.js. Only decimal values seem to be arriving as NULL, while integer or string values work fine. Below is the code snippet: salvarProdutos: function ( ...

What could be causing the sluggish performance of my wysiwyg editor in Vue.js?

I've been exploring the use of a wysiwyg editor on my webpage. Implementing simple two-way data binding with v-model="text" and straightforwardly outputting <div v-html="text"></div>. As a beginner in vuejs, I have encountered a performanc ...

Error message: Unidentified variable encountered during API fetch using Axios props

Introduction to My Main Component This component, named "Home", is a straightforward one that simply passes the fetch variable to another component. <template> <Page actionBarHidden="true"> <ComponentA :api="api.somevariable" ...

What is the best way to synchronize the state of a component with the updated value in a Vuex store?

Within my Vuex store, I have implemented mutations that receive a message from one component and are responsible for showing/hiding a prompt message in another component (similar to displaying a "You are logged in" prompt after a successful login): setPro ...

Trouble with V-if not updating after property is modified within an async TypeScript function

There is a scenario where one HTML element becomes hidden after an async call returns from the server, while another HTML element is displayed: <template> <div v-if="!showElementTwo">Element 1</div> <div v-if="show ...

A step-by-step guide on how to capture user input in Vue.js after the "

Is there a way to capture the character entered after a key is pressed or after the user presses the enter key? I tried using the npm package npm i vue-keypress, but I couldn't figure out how to capture the characters. Can you suggest another method ...

Adding a character at the current cursor position in VUE JS

My quest for inserting emojis in a textarea at the exact cursor position has led me to an extensive search on Vue JS techniques. However, most resources available online provide solutions using plain Javascript. Here is the code snippet I am working with: ...