This is my first time deploying a nuxt app to heroku, I've followed the instructions I've found on nuxt guide.
Created the heroku app & added the following configuration:
added the procfile with the following line: web:nuxt start
And it worked, When I go to: https://coupongb-nuxt.herokuapp.com/ the website opened and the products are loaded but it seems the "infinit scrolling with uses $axios plugin isn't working, As well as opening a product page "by clicking a product card".
So I guess it's $axios that's making that error, Seems it's baseURL is localhost:3000 istead of the website domain
So my question is How to make this.$axios.$get(...) point to the website domain instead of localhost:300
You will need to set environment variables for this. https://cli.vuejs.org/guide/mode-and-env.html#environment-variables
Where ever you are configuring Axios have it look at the environment variable to set the baseURL, example:
Axios.defaults.baseURL = process.env.APP_API
Then create your .env files in the root of your directory:
APP_API=https://coupongb-nuxt.herokuapp.com/
Alternatively you can change the baseurl inline whenever you are creating a call to your api. For example
this.$axios.get('/example-path')
would be replaced with
this.$axios({ url: '/example-path', baseURL: 'https://coupongb-nuxt.herokuapp.com' })
Alternatively to Tim´s response.
Add this at the top of your file:
const DEV = process.env.NODE_ENV !== 'production'
This way DEV will be true if enviroment is for development and false if it´s for production.
Below inside your export default object, you add the axios object:
axios: {
baseURL: development ? '' : 'https://your-heroku-url.com/'
}
And thats it, this way you don´t have to write a URL and the base URL every time you use axios.
Related
I'm developing a full-stack web app, which has both a frontend and a backend. In production, my frontend will be hosted at https://frontend.com, and my backend at https://backend.com. It seems reasonable to hardcode the address https://backend.com in my frontend code.
However, when I am testing the app locally, I'll want to spin up the backend at, say, localhost:8000, and redirect my frontend to this address instead. My question is: what's the easiest/most elegant way to do this?
One approach is to manually change the frontend code to point to localhost:8000 for local testing, and then change it back before deploying. However, this is quite annoying, and it's too easy to forget to change it back.
An approach I've used in the past is:
Create a file server.js containing:
const LOCAL_SERVER = "http://localhost:8000"
Import this file in my frontend HTML:
<script src="server.js"></script>
Set a fallback to the remote/production server in my JS scripts:
let SERVER = typeof LOCAL_SERVER === 'undefined' ? 'https://backend.com' : LOCAL_SERVER
Add server.js to my .gitignore.
This works, but it feels kind of hacky, and it pollutes my production code with references to this (possibly non-existent) server.js and LOCAL_SERVER constant. I'm wondering if anyone has a better way.
If your real backend & local backend use the same port, a simple solution is to add the following line to your hosts file:
127.0.0.1 backend.com
I have Vue.JS front app with nodeJS backend based on expressJS. ExpressJS also used as web server for statically built Vue.JS app
Front app communicates with express backend via rest and websocket. It uses url host from window.location instance and easily communicates with backend
In production mode, when built application in static expressJS server area, everything work perfect
In dev mode, Vue use it's own web server, and backend urls based on window.location are incorrect because no expresJS on same host and port.
So my question is it possible change some code blocks if running in dev mode ?
Like something this :
if( devmode)
{
const url = "http://somebackendhost/rest"
}
else {
const url = location.host ....
}
}
I will assume you are developing your Vue app using Vue CLI
Changing app behavior depending on environment
In Vue CLI you can use Environment Variables
if(process.env.NODE_ENV === "development")
{
}
This works thanks to Webpack's Define plugin and big advantage is that process.env.NODE_ENV is replaced at build time by the real value. So in production build Webpack will see just if("production" === "development") {} and happily removes the code in optimization phase because it knows this can never be true
Better solution
But I would not use this approach for your problem. Using different API server (not same as the server used for serving Vue SPA) can easily lead to CORS problems
Exactly for this use case, Vue CLI (and Webpack Dev server used under the hood) supports proxying
vue.config.js
module.exports = {
devServer: {
proxy: {
'^/api': {
target: 'http://localhost:58300/',
ws: true, // websockets
changeOrigin: true,
}
}
},
},
This config makes Vue Dev server to proxy any request to /api to other server running at http://localhost:58300/ (your node/express app) and change the origin (so browser thinks response came from the dev server)
All of this can be done without Vue CLI but you will need to set it up by yourself in Webpack config...
The problem
You can't access this information from your browser.
But there are three solutions:
Solution #1
On compilation time create a variable in code which defines devmode (const devmode = true;)
Solution #2
Because your bundler can minify your variable names or changing the scope for security reasons, may be the situation where you can't access it.
So second solution is to define devmode in your localStorage.
Solution #3
Third solution is almost the best.
If you are developing, you are probably accessing your web app via localhost.
location.hostname will return the name of host, so you can make something like:
const devmode = location.hotname == 'localhost';
Best solution
Do not do this. Develop a fully working web app using local REST API and define the URL of REST API in some variable, so when you are preparing your production app, you or compiler just changes the URL adress variable in code of your REST API.
Why is this the best solution?
Because it do not impacts your end-user's performance and they will be loading less code, which is the best practise.
Post Scriptum
Don't forget to remove all devmode codepaths when compiling production version!
I will like my baseUrl to be my domain name instead of localhost. Something like https://domain/api/post/allpost. I developed with nuxt and deployed with zeit now. But when i try to access the api using mydomain/api/post/all, it fails. But it works only in localhost:3000/api. I use axios.
in nuxt.config.js
...
env: {
baseUrl: process.env.baseUrl || "http://localhost:3000"
}
in nuxt page
Axios.get(`${process.env.baseUrl}/api/post/all`)
even when i change the baseUrl from localhost to "https://my-domain.com", It still cannot call my api routes. Please i need help
I just created a react-node-SQL app and I want it to run on Google Cloud (not firebase)
My React app runs on different port and my node app runs on different port.
I followed this article and added this line in my react-app package.json but I didn't worked out i.e href in button was still going to localhost:8081 but It didn't worked
I had my node running on port 8080, In package.json of my react app i added "proxy": "http://localhost:8080/" and in button when I did href="/api/status" it was going to localhost:8081 on which the react app was running
Now, Is it possible to run both node and react under the same project? or we need to create separate project for them.
[Update:] I am using webpack, In my webpack config file, I added this
devServer: {
proxy: {
'/': 'http://localhost:8080'
}
},
The problem with this, that even in my react app, on Startup (running on 8081) when it opens the webpage localhost:8081/ it throws an error saying cannot get the page
but if I do something like this
devServer: {
proxy: {
'/api': 'http://localhost:8080'
}
},
it opens the page homepage normally. Now my api and callback uRL after authentication aren't configured with have prefix as api.
Basically, when you do an ajax request from react app, like axios or fetch it will use the proxy: <..> for the backend url. But, href doesn't work with proxies. In that case you need to manually configure proxy using the setupProxy.js documented in the manual proxy page.
Check out this issue:
Same error here, it still routes to localhost:3000/api/auth/google, my
CRA version is 2.1.3 It seems http-proxy-middleware is the only
working way. I have to Configuring the Proxy Manually
From the react doc:
If the proxy option is not flexible enough for you, you can get direct
access to the Express app instance and hook up your own proxy
middleware.
You can use this feature in conjunction with the proxy property in
package.json, but it is recommended you consolidate all of your logic
into src/setupProxy.js.
Using Preact CLI is it possible to set the path where the app will be hosted outside of the root directory?
For instance hosting the app at http://mywebsite.com/relativepath/index.html
You have several problems to solve:
1. Get Webpack to output the correct paths in your html
This is done via creating a preact.config.js in your root folder, and put the following in there
export default (config) => {
config.output.publicPath = '/relativepath/';
};
2. Set your navigation and assets links in your app
The best way to solve it in my opinion is to use a global variable which you can be used in your app. So again, edit the preact.config.js to the following:
export default (config, env, helpers) => {
config.output.publicPath = '/relativepath/';
// use the public path in your app as 'process.env.PUBLIC_PATH'
config.plugins.push(
new helpers.webpack.DefinePlugin({
'process.env.PUBLIC_PATH': JSON.stringify(config.output.publicPath || '/')
})
);
};
3. Routing
When using your preact app, it should be no problem to navigate. However, if you try to load a fresh URL e.g. www.myserver.com/relativepath/mything/9, the server doesn't know that it should load your single page app living at www.myserver.com/relativepath/index.html
You have two options:
a) Server-side routing
Make sure your all the requests to relativepath (including e.g. relativepath/mything/9) will be rewritten to your app's relativepath/index.html (in case of using Apache).
Then your Javascript can process the routes, e.g. preact-router
b) Client-side routing (recommended)
The easier option for enabling reloading of URLs is to use hash urls, thereby avoid going through the server when loading a URL.
Your URLs will look something like www.myserver.com/relativepath/#/mything/9
The server ignores the part after # and only loads (hopefully) /relativepath/index.html
You can use e.g. the preact-router with Hash History to avoid server-side routing, read about it here https://github.com/developit/preact-router#custom-history
I'm proxying from http-proxy-middleware to the preact-cli dev server and these settings worked for me in preact.config.js
export default (config, env, helpers) => {
config.output.publicPath = '/relativepath';
config.devServer.devMiddleware.publicPath = "/relativepath";
};