Trying to rewrite path of request with http-proxy-middleware. But trouble is that when i am writing such code:
proxyMiddleware('/service/api', {target: 'http://192.168.70.99:8078/'});
It means that path like /service/api/export/1 will be redirected to http://192.168.70.99:8078/service/api/export/1; But I need to redirect it to http://192.168.70.99:8078/export/1. How can I do that?
You can pass the pathRewrite opiton and inside it use regex pattern to remove the path that you don't need:
proxyMiddleware('/service/api', {
target: 'http://192.168.70.99:8078/',
pathRewrite: {
'^/service/api':'' //remove /service/api
}
});
Related
I have a function that allows you to create a folder in the directory where the server is located, and upload files there
And I'm trying to access them via a direct link, like this
http://localhost:5000/attachments/1618413024408--1.jpg
Because, the file is located here
But why can't I access it?
Cannot GET /attachments/1618413024408--1.jpg
Express itself provides an easy to use implementation for this express.static(root, [options]).
Simply add this add the right position in your code:
app.use('/attachments', express.static(path.join(__dirname, 'attachments')))
Make sure that path.join(__dirname, 'attachments') points to the right directory (with a simple console.log) otherwise just adjust it.
Documentation: https://expressjs.com/en/starter/static-files.html
try to use express function sendFile
https://expressjs.com/en/api.html#res.sendFile
something like this
app.use('/attachments/:filename', (req, res) => {
const myIms = <path to directory>
const filePath = myIms + '/attachments/' + req.filename
res.sendFile(filePath, {
headers: {
'Content-Type': 'image/jpg'
}
})
})
or express download function https://expressjs.com/en/api.html#res.download
Im trying to deploy cors-anywhere on Google Cloud Functions. Im supposed to provide the url after gcp's link.
It looks like this :
https://us-central1-my-project.cloudfunctions.net/my-function/http://dummy.restapiexample.com/api/v1/employees
but it's transformed to :
https://us-central1-my-project.cloudfunctions.net/my-function/http:/dummy.restapiexample.com/api/v1/employees
All the double slashes after the host are transformed to simple ones.
I tried replacing req.url to transform http:/ to http:// but still wont work. Maybe this needs to be fixed in the webserver level.
Here's my function in GCP
var cors_proxy = require('cors-anywhere').createServer({
requireHeader: ['origin', 'x-requested-with'],
removeHeaders: [
'cookie',
'cookie2',
],
// See README.md for other options
});
exports.myFunction = (req, res) => {
req.url = req.url.replace('/my-function/', '/'); // Strip '/my-function' from the front of the URL, else the proxy won't work.
return cors_proxy.emit('request', req, res);
};
Anyone tried to deploy this in a serverless function?
You're using req.url which contains a normalized version of the request URL. You'll want to use req.originalUrl which, as the name suggests, retains the original requested URL. See Express docs for more info.
My Node.js application sends a response to load the following url in an iframe
http://localhost:3000/fileloadsuccess.html?fname=abc.txt
I get the error
EONET : no such file or directory exists
I have set the routing as
app.get('/fileloadsuccess.html?fname=:fid', function(req,res){
res.sendfile(__dirname + '/fileloadsuccess.html?fname=:fid');
});
What could be the issue?
You can not use query string parameters with res.sendFile().
You also could try so serve fileloadsuccess.html as static file:
https://expressjs.com/en/starter/static-files.html
Or continue to use res.sendFile() like:
res.sendFile('fileloadsuccess.html', { root: __dirname });
To get query string parameters you can use req.query
http://expressjs.com/en/api.html#req.query
I am working on migrating an existing app to a new tech stack that uses Node and MongoDB on the backend and Vue on the frontend. I have a fairly large number of pages that will need to be redirected to new URLs (over 50). I know I can do something like this in the frontend:
const appRouter = new Router({
mode: 'history',
routes: [
{ path: '/a', redirect: '/a2' },
{ path: '/b', redirect: '/b2' },
{ path: '/c', redirect: '/c2' },
]
});
However it doesn't strike me as particularly elegant. I could see keeping the redirects in another file and importing them to keep my router file neater, but that seems like just a formatting benefit.
I'm wondering how other people handle a large number of redirects in Vue? Would this be better to do at the server-level with Node?
If boilerplate is the problem, you can use something like:
const router = new VueRouter({
routes: [
{ path: '/([abc])', redirect: to => {
returect to.path + '2'; // to.path will be like '/a'
}}
]
})
Notice that the part inside () is a regex that can be customized.
I have a fairly large number of pages that will need to be redirected to new URLs
When we talk about redirecting a Uniform Resource Locator (URL) in the context of a Single Page Application (SPA) like Vue with Vue Router, hosted by a web server like Node.js, we might mean one of two things:
we've changed the route of a view within our Vue SPA
we've changed the location of our SPA (the resource) from one location to another.
To determine which kind of redirect you need to do, we can examine how the URL will change. URLs are made up of these components:
scheme:[//[user[:password]#]host[:port]][/path][?query][#fragment]
By default, Vue Router uses the #fragment (hash) portion of the URL to change views, so if this changes then we should redirect using Alias or Redirect.
If any other portion of the URL changes, we should have Node.js return an HTTP status code for redirect, like 301 Moved Permanently or 302 Moved Temporarily.
Normally the solution from #acdcjunior is good enough, but sometimes you may prefer hooking beforeRouteUpdate to implement the redirect.
You can check vue-router: dynamic Routing for more details.
Below is one simple sample is from the official document:
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
if ( to.match(new RegExp('your_regex_expression'))) {
next('redirect_url')
} else {
// default
next()
}
}
}
Or in main.js by using global guards:
import router from './router'
router.beforeEach((to, from, next) => {
if ( to.match(new RegExp('your_regex_expression'))) {
next('redirect_url')
} else {
// default
next()
}
})
I'm using the following get:
app.get("/:project/*", auth, function (req, res) {
Then parsing against a config file to load a directory dynamically:
var path = req.params[0] ? req.params[0] : "index.html";
res.sendfile( path, { root: "./builds/" + config[req.params.project].dir + "/dist/" } );
Which works great, only problem is that it requires my urls to end with a "/" if I'm going to the default (index.html). For example, I have to use http://server.com/some_project/ and if the trailing slash isn't there it throws a Cannot GET /some_project error. Curious if there's a way around this?
app.get("/:project/?*", ...)
Add the question mark. That should allow you to do with or without the trailing slash.