Why Proxy not working in browser (NuxtJS+Axios)? - javascript

In server rendering Proxy is working fine. Request is going to custom-server.com/v1/places. But in browser request is going to current-domain.com/api/places
Why it is not working in browser? Proxy working only in server side? Please, help.
I have NuxtJS config:
require('dotenv').config();
export default {
mode: 'universal',
buildModules: [],
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy',
['#nuxtjs/dotenv', { systemvars: true }],
],
axios: {
proxy: true,
credentials: true,
},
proxy: {
'/api': {
target: "http://custom-server.com",
pathRewrite: {
'^/api' : "/v1"
},
changeOrigin: true,
},
},
}
My component:
<script>
export default {
data() {
return{
placesServer:false,
placesBrowser:false,
}
},
async asyncData ({ $axios }) {
// Here is all is fine
let response = await $axios.get("/api/places");
return {
placesServer:response.data,
};
},
created(){
if (process.browser){
// Here is not working =(
this.$axios.get("/api/places").then((response)=>{
this.placesBrowser = response.data;
});
}else{
// Here is working fine!
this.$axios.get("/api/places").then((response)=>{
this.placesBrowser = response.data;
});
}
}
}
</script>

If your API URL is =http://custom-server.com/api/v1/api/places
Need to following change of Given code and need to understand the vuejs/Nuxtjs lifecyle
export default {
mode: 'universal',
buildModules: [],
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy',
['#nuxtjs/dotenv', { systemvars: true }],
],
axios: {
proxy: true,
},
proxy: {
'/api': {
target: "http://custom-server.com",
pathRewrite: {
'^/api' : ""
},
},
},
}
and the given code inside created() hook is need to change another life cycle maybe. or need to move inside method() or as per need your requirements.

adding prefix to axios in nuxt.config.js helped me
axios: {
proxy: true,
credentials: true,
prefix: '/api/'
}

Related

Vue webpack devServer proxy prepending fetch url with vue-router params

I have vue3 project using a webpack devServer proxy and keep getting a 404 when running a fetch to an api due to the url being prepended with an incorrect value. This only occurs on pages that are using vue-router params.
example page url is -
http://localhost:8081/edit/206
correct fetch url should be -
http://localhost:8000/api/enquiries/getenquiry/206
actual fetch url -
http://localhost:8000/edit/api/enquiries/getenquiry/206
fetch command -
let response = await fetch(`api/enquiries/getenquiry/${id}`, {
method: 'GET',
})
vue-router -
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import NewEnquiries from '../views/enquiries/NewEnquiries.vue'
import EditEnquiry from '../views/enquiries/EditEnquiry.vue'
import MailboxesView from '../views/system/mailboxes/MailboxesView.vue'
const routes = [
{ path: '/', name: 'home', component: HomeView },
{ path: '/new', name: 'new', component: NewEnquiries },
{ path: '/edit/:id', name: 'editenquiry', component: EditEnquiry },
{ path: '/mailboxes', name: 'mailboxes', component: MailboxesView }
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
vue.config.js -
const { defineConfig } = require('#vue/cli-service')
const AgentKeepAlive = require('agentkeepalive');
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
logLevel: 'debug',
agent: new AgentKeepAlive({
maxSockets: 100,
keepAlive: true,
maxFreeSockets: 10,
keepAliveMsecs: 100000,
timeout: 6000000,
freeSocketTimeout: 9000000 // free socket keepalive for 9000 seconds
}),
onProxyRes: (proxyRes) => {
const key = 'www-authenticate';
proxyRes.headers[key] = proxyRes.headers[key] && proxyRes.headers[key].split(',');
}
}
}
}
})
What works -
adding the following pathRewrite to remove the prepended "edit" acts a workaround but obviously not a good solution going forward. Where am i going wrong here?
pathRewrite: { '^/edit': '' }

Exportpathmap in next.config.js set dynamic routes in NextJS

I am trying to set dynamic routes by using Exportpathmap() in nex.config.js. Static routes is working fine as I want but when I am trying to apply dynamically, the dynamic URL is not working and redirected me to main URL.
Please help me do fix this issue.
Thansk in advance.
Here is my next.config.js
return{
reactStrictMode: true,
env: env,
trailingSlash : true,
eslint: {
ignoreDuringBuilds: true,
},
swcMinify: true,
images: {
domains: ['cdn.pixabay.com', 'pixabay.com', 'cdn.landrrapp.io'],
loader: 'akamai',
path: '',
},
exportPathMap: async function (
defaultPathMap,
{ dev, dir, outDir, distDir, buildId }
) {
return {
'/404': { page: '/404' },
'/forgot-password': { page: '/forgot-password' },
'/login': { page: '/login' },
'/editor/[id]': { page: '/editor/[id]' },
}
},
}
I am facing issue with this one '/editor/[id]': { page: '/editor/[id]' },
NEXT JS: Build exportPathMap for a dynamic page Route
Above was lokks fine but I am unable to understand "
import { PAGE_ROUTES } from '../constants/config';
" this file data.

Adding the proxy in vite takes me to that proxy url on my localhost. I only want to use it for api calls to backend

Here is my vite.config.ts:
import { defineConfig } from 'vitest/config'
import vue from '#vitejs/plugin-vue'
import { quasar, transformAssetUrls } from '#quasar/vite-plugin'
const path = require('path');
// https://vitejs.dev/config/
export default defineConfig({
test: {
globals: true
},
plugins: [
vue({
template: {
transformAssetUrls
}
}),
quasar({
sassVariables: 'src/assets/scss/quasar-variables.sass'
})
],
resolve: {
alias: {
"#": path.resolve(__dirname, './src'),
},
},
server: {
proxy: {
'/socket': {
target: 'wss://abc-website.com:4221/',
changeOrigin: true,
ws: true,
rewrite: (path) => path.replace('^/socket', ''),
},
'/streaming/': {
target: 'https://abc-website.com/',
changeOrigin: true,
},
'/': {
target: 'https://abc-website.com/',
changeOrigin: true,
secure: false,
ws: true
},
}
}
})
whenever my application is loaded it takes me to the https://abc-website.com while being on my locahost port.
I want to use above url for backend api calls only like https://abc-webite.com/api/auth.
Also i set the baseURL to "api/" after setting the proxy in vite.config.ts.
Also after the slight change it calls the REST api like https://localhost:3000/auth, i should rather be https://locahost:3000/api/auth
Vite proxy doesn't seems to work properly for me.
I think you could something like this:
server: {
proxy: {
// ... your other proxies
'/api': {
target: 'https://abc-website.com/',
changeOrigin: true,
secure: false,
ws: true,
rewrite: (path) => path.replace(/^\/app/, ''),
},
}
}
Then all your requests to sites like localhost:3000/api/my-endpoint should be proxied to https://abc-website.com/my-endpoint. You cannot proxy all "basic" requests, 'cause they are reserved for serving everything else, all the assets, index.html's and etc., but I'm also kind

How to use different settings in nuxt.config.js depending on the environment

Thanks to dotenv I can use environment variables in my nuxt.config.js file
Only I have whole settings that need to disappear depending on the environment. In some cases, I know how to use a tertiary condition, but in others, I cannot.
For example, for my dev environment, I have to do this :
export default {
head: {
title: process.env.APP_NAME,
},
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
'#nuxtjs/auth',
'#nuxtjs/dotenv'
],
axios: {
baseURL: 'http://app.test/api',
},
…
}
And for my production environment I have to add some things
export default {
head: {
title: process.env.APP_NAME,
},
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
'#nuxtjs/auth',
'#nuxtjs/dotenv',
'#nuxtjs/proxy'
],
axios: {
prefix: '/api/',
proxy: true
},
// also a new bloc
proxy: {
'/api/': {
target: 'https://my-api.app/'
}
},
…
}
How to do that simply?
The Nuxt config file is simply a normal .js file.
You can create and modify the exported object the same as any other object.
const isProd = true;
const nuxtConfig = {
head: {
title: process.env.APP_NAME,
},
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
'#nuxtjs/auth',
'#nuxtjs/dotenv'
],
axios: {
baseURL: 'http://app.test/api',
},
};
if(isProd) {
nuxtConfig.modules.push('#nuxtjs/proxy');
nuxtConfig.axios.proxy = true;
nuxtConfig.proxy = {
'/api/': {
target: 'https://my-api.app/'
}
}
}
export default nuxtConfig;
Use inline conditionals
If you only have minimal differences between environments, maintain the default nuxt.config.js structure and just use inline conditions (ie ternary operator) wherever you need.
Example:
head: {
title: process.env.NODE_ENV === 'prod' ? "my prod title" : "my dev title"
}
You can also chain multiple conditions...
head: {
title: process.env.NODE_ENV === 'prod1' ? "my prod title 1" : process.env.NODE_ENV === 'prod2' ? "my prod title 2" : "my dev title"
}
... however now you have more complexity. If it gets too deep, then maybe it's time to have logic outside of the main export object, as
#Jordan suggested.

Next.js v10 Internalisation - getStaticProps always return default locale

I'm trying to setup a new Next.js version project with internalisation based on domain routing.
I have my next.config.js with the following lines:
i18n: {
locales: ['de-DE', 'en-US'],
defaultLocale: 'en-US',
domains: [
{
domain: 'mydomain.com',
defaultLocale: 'en-US'
},
{
domain: 'mydomain.de',
defaultLocale: 'de-DE'
}
],
localeDetection: false
},
and I have my catch-all-routes page like this:
import React, { Fragment } from 'react';
import * as api from '../api';
import Header from '../components/Header';
import Footer from '../components/Footer';
import Sections from '../components/Sections';
function Page({ page = {} }) {
return (
<Fragment>
<Header />
<Sections {...page} />
<Footer />
</Fragment>
);
}
export async function getStaticProps(context = {}) {
const { params = {}, locale } = context;
const pathname = params.slug ? params.slug.join('/') : '/';
const page = await api.fetchPage(pathname, locale);
return {
props: {
page
},
revalidate: 1
}
}
export async function getStaticPaths() {
// this will be generated, hardcoded this pages for testing
return {
paths: [
{
params: {
slug: ['produkte']
},
locale: 'de-DE'
},
{
params: {
slug: []
},
locale: 'de-DE'
},
{
params: {
slug: ['products']
},
locale: 'en-US'
},
{
params: {
slug: []
},
locale: 'en-US'
}
],
fallback: true
};
}
However everytime when I'm trying to preview locally the German version, it returns me English one and I see that inside getStaticProps the value of locale is always en-US. I'm trying to access the page with http://localhost:3000/?__nextLocale=de-DE as an url.
What's missing here to make it work properly?
Thanks!
You need to whitelist localhost as well, otherwise it will fallback to default locale.
so you could do something like this in your next.config.js:
i18n: {
localeDetection: false,
locales: ['en-US', 'de-DE'],
defaultLocale: 'en-US',
domains: [
{
domain: 'localhost:3000',
defaultLocale:'en-US',
http: true,
},
{
domain: 'mydomain.com',
defaultLocale: 'en-US'
},
{
domain: 'mydomain.de',
defaultLocale: 'de-DE'
}
],
}
Then when accessing localhost, the defaultLocale should define the locale it will open for you.. in this case, en-US.
so in the browser you can see that if you do localhost:3000 it will open in en-US. And also it you can access it english pages under localhost:3000/en-US/
Aaaaand, the german ones will be available under localhost:3000/de-dE.

Categories