Rewriting Webpack Proxy URLs - javascript

I'm using Webpack Dev Server to proxy my files from an external url, that's because I'm using it to develop locally and proxying the PHP/Twig files from the server, so that way I don't need to set up all the back-end locally.
But the problem is that I need to rewrite the assets urls to pull these files from my local machine, not from the proxy. Right now, when I open my localhost, all the assets are being loaded from the server. i.e: http://mycoolwebsite.com/core/somefolder/assets/styles.css
And I need to replace that to pull from my localhost, like this:
/assets/styles.css
This is what I have now:
devServer: {
compress: true,
port: 9000,
proxy: {
'*': {
target: 'http://mycoolwebsite.com',
changeOrigin: true,
secure: false
}
}
Any clue?
Thanks!

you want all request that go to your server "http://mycoolwebsite.com/**"
to go to your local machine: "http://localhost:9000/" (assuming its running on port 9000)
so try this:
proxy: {
'/assets/**': {
target: 'http://localhost:9000',
secure: false,
pathRewrite: function(req, path) {
//use the pathRewrite to modify your path if needed
return path;
}
}
now it shouldn't make any difference what server you are actually calling. every request that includes '/assets/' should go to your localhost. (I can not test it atm)

Related

Electron + Vue API requests fall to app://

I've built a Vue app and added Electron to it. I used Vue CLI Plugin Electron Builder
It's ok in development mode, all API requests fall on address which is written in my vue.config.js:
proxy: {
'^/api': {
target: 'http://my-api:3000',
changeOrigin: true
},
},
For example, Axios POST request /api/open_session/ falls to http://my-api/api/open_session as needed.
When I build the project it creates an app:// protocol to open the index.html file.
But it also makes all url paths beginning with app:// including API requests.
My background.js:
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
}
else {
createProtocol('app');
// Load the index.html when not in development
win.loadURL('app://./index.html');
}
I want these paths to be directed to my API, while open all my files as usual (via app protocol)
Well, it's been a longer time and I coped with that on my own. However, here's an answer I came across some forums for those who are struggling with the same issue:
Firstly, I modified my vue.config.js:
proxy: {
'^/api': {
target: 'http://127.0.0.1:3000',
changeOrigin: true
},
},
Then, I made some changes in main.js - added a session variable:
const sesh = session.defaultSession.webRequest.onBeforeSendHeaders({
urls: ['*://*/*']
}, (details, callback) => {
// eslint-disable-next-line prefer-destructuring
details.requestHeaders.Host = details.url.split('://')[1].split('/')[0]
callback({
requestHeaders: details.requestHeaders
})
})
that defines app's behavior when requests get called. Also, I've added a session value to webPreferences:
const win = new BrowserWindow({
width: 1500,
height: 700,
title: "Title",
webPreferences: {
session: sesh,
nodeIntegration: true,
webSecurity: false
}
})
And, finally, load my index.html via app protocol
createProtocol('app');
win.loadURL('app://./index.html');
In result, all my requests got redirected to my server.
Forgive me for not knowing the source, if the author of the code is reading this, you can surely mark yourself in comments :)

How to set proxy for different API server using Nuxt?

So I have 2 applications:
an Adonis API server accessible via http://10.10.120.4:3333
A SSR app using Nuxt.js accessible via http://10.10.120.4:80
The Nuxt.js app is accessible outside using url http://my-website.com. I have axios module with this config
axios: {
baseURL: '0.0.0.0:3333/api',
timeout: 5000
}
Now the problem is, when I am requesting data with asyncData it works, but when the request was made from outside asyncData, say created() for example, it throws an error saying the url http:0.0.0.0:3333 is missing which is true since it's already running in the browser and not in the server.
The first solution that I've tried is to change the baseURL of the axios module to this
axios: {
baseURL: 'http://my-website.com/api',
timeout: 5000
}
But it seems nuxt server can't find it, so I think the solution is to make proxy and installed #nuxtjs/proxy.
And this is my proxy config in nuxt.config.js
{
proxy: {
'/api': 'http://my-website.com:3333',
}
}
and then I just changed my axios baseURL to
http://my-website.com/api
But again it didn't work.
My question is, how do you deal with this kind of scenario? Accessing different server from browser?
When using Proxy in a nuxt project you need to remove baseUrl and set proxy to true as seen below.
axios: {
// Do away with the baseUrl when using proxy
proxy: true
},
proxy: {
// Simple proxy
"/api/": {
target: "https://test.com/",
pathRewrite: { "^/api/": "" }
}
},
when making a call to your endpoint do:
// append /api/ to your endpoints
const data = await $axios.$get('/api/users');
checkout Shealan article

Express serves static files that are not in root directory

I have a website with a lot of HD videos so I want to put the videos files outside of web root directory.
Here is my web root directory:
/var/node/myapp
For some basic static files like javascript, css... I put them in public directory.
/var/node/myapp/public
For video files I want to put here
/hdd/videos
This is my current serve static code:
app.use(serveStatic(path.join(__dirname, 'public'), {
maxAge: keys.conf.maxAge,
etag: true,
setHeaders: setCustomCacheControl
}));
function setCustomCacheControl (res, path) {
if (serveStatic.mime.lookup(path) === 'text/html') {
res.setHeader('Cache-Control', 'public, max-age=0')
}
}
You can set multiple static directories. Example:
app.use(express.static('public', {etag: true, maxAge: keys.conf.maxAge}));
app.use(express.static('/hdd/videos'));
However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve.
Document for express static file in here
If you want to have a directory accessed outside of the root web server you'll need to go up a directory level via ... You didn't specify where exactly /hdd/videos is in relation to your root directory, but it should change to look something like this:
var videosDirectory = __dirname + '/../../hdd/videos';
app.use(serveStatic(videosDirectory, {
maxAge: keys.conf.maxAge,
etag: true,
setHeaders: setCustomCacheControl
}));
function setCustomCacheControl (res, path) {
if (serveStatic.mime.lookup(path) === 'text/html') {
res.setHeader('Cache-Control', 'public, max-age=0')
}
}
You can create a symlink under /var/node/myapp/public to point to /hdd/videos:
On Linux/Unix/OSX, for example:
ln -s /hdd/videos /var/node/myapp/public/videos
This way you don't expose your entire root directory, and you can separate where you store the actual videos from where you serve them without copying or moving them when they're added/removed/etc.
When the user hits your route /videos it will look for it under /var/node/myapp/public as per your static route. It will see videos as a link and follow that link to /hdd/videos where the videos will be available.

Using Gulp + BrowserSync + Connect PHP for Multiple Projects

I've put together a boilerplate gulp setup for myself when setting up a new webapp project and I'm having some trouble with using BrowserSync, and Connect-PHP in tandem.
Here's are my tasks for spinning up the server and starting BS:
gulp.task('php', function() {
php.server({base: 'app', port: 8030, keepalive: true});
})
gulp.task('browserSync',['php'], function(){
browserSync.init({
proxy: '127.0.0.1:8030',
port: 8080,
open: true,
notify: false
});
})
The problem is that every time I set up a new project, I have to change the port for the php server and proxy url to a new, previously unused one.
Is there a way I can avoid having to choose a new port number each time?
For further reference, it appears this question was asked before but not answered here: Can't use gulp (with gulp-connect-php and gulp-browser-sync) with multiple projects

restangular remove and put error net::ERR_NAME_NOT_RESOLVED

i have this error when i try to do a put or a remove with restangular the post and the getList() works perfectly,
when i'm going to edit mi object i create a object like this
edited = Restangular.copy(danger);
danger is my modelobject from my template in a table i just grab the object from the table, the object is fine.
then in my function i just try to do
edited.put();
and the error is OPTIONS http://dangers/1/ net::ERR_NAME_NOT_RESOLVED
like restangular is not generating the url, the post url is http://localhost:8000/dangers/
i'm using gulp with a proxy in the dev enviroment to capture the api requests
gulp.task('server', ['build'], function() {
gulp.src('./build')
.pipe($.webserver({
port: 8080,
host: 'localhost',
fallback: 'index.html',
livereload: {
enable: true,
port: 8181
},
open: true,
// django app
proxies: [{
source: '/api',
target: 'http://localhost:8000/api'
}]
}));
});
This was my error django restframework needs the trailing slash in every url the solution was to add in the config of restangular
RestangularProvider.setRequestSuffix('/');

Categories