Simple case: I have app1 - which is an install of ghost (site-blog.herokuapp.com). I have app2, which is a custom express.js app (site.herokuapp.com).
I want to serve the blog from site.herokuapp.com/blog.
For Ghost, here's part of my config.js
production: {
url: process.env.BLOG_IDENTIFIER_URL,
fileStorage: false,
database: {
client: 'postgres',
connection: process.env.DATABASE_URL,
debug: false
},
server: {
host: '0.0.0.0',
port: process.env.PORT
}
},
BLOG_IDENTIFIER_URL is set to site.herokuapp.com/blog.
For the express.js app, I have the following routing (for /blog):
router.all('*', function(req, res) {
// blog page is actually a ghost!
var blog_url = 'http://localhost:2368';
if (process.env.NODE_ENV === 'production') {
blog_url = 'http://site-blog.herokuapp.com';
}
req.headers.host = blog_url;
require('http-proxy').createProxyServer().web(req, res, { target: blog_url });
});
This works absolutely fine locally, but when I push both the repos to heroku, and try to visit site.herokuapp.com/blog, I get just a blank page and nothing in the logs. The request fails though:
I have tried a lot of stuff, both from SO and from the rest of the visible internet. Nothing seems to work. I'm stuck here for the last 4 hours. If you have anything that might help, please please leave a comment or an answer.
Related
I'm trying to proxy requests from a Svelte app to a different port, where my backend API runs. I want to use a rollup proxy in the dev environment.
I read the alternative of using a webpack proxy here, but I want to give rollup proxy a try.
This is not an issue in production.
As suggested, I tried configuring rollup-plugin-dev However, whenever I make a request to weatherforecast I still get an CORS error. Below is my configuration and the call:
import dev from 'rollup-plugin-dev'
// other code
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
dev({
proxy: [{ from: '/weatherforecast', to: 'https://localhost:7262' }]
}),
// other code
];
and App.svelte looks like this:
<script>
import { onMount } from "svelte";
const endpoint = "/weatherforecast";
onMount(async function () {
try {
const response = await fetch(endpoint);
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
});
</script>
Any help in solving this issue is appreciated.
What's happening is the proxy is passing through the CORS headers un-touched, so you're basically interacting with the API as though the proxy wasn't even there, with respect to CORS.
I'll note that you can get around this in dev, but keep in mind this problem will come up in production too, so you may just need to rethink how you're getting this data.
For development though, you can use something like cors-anywhere. This is a middleware that you can run through your dev server that can rewrite the headers for you.
To configure rollup-proxy on dev environment, you need to remove the call to the serve method, call the dev method and move the proxy calls inside the dev method:
import dev from 'rollup-plugin-dev'
// other code
export default {
input: 'src/main.js',
output: {
// other code
commonjs(),
// enable the rollup-plugin-dev proxy
// call `npm run start` to start the server
// still supports hot reloading
!production && dev({
dirs: ['public'],
spa: 'public/index.html',
port: 5000,
proxy: [
{ from: '/weatherforecast', to: 'https://localhost:7262/weatherforecast' },
],
}),
// line below is no longer required
// !production && serve(),
// other code
];
I am having an issue with the Cloudinary Node SDK where the Admin Resources endpoint is occasionally throwing a 302 error. Their support suggested that I proxy the request so that I can log the response between my api and their SDK and ultimately get a better idea of what might be causing the problem (in the end they're hoping to see the Location headers that are in the Response).
One of their suggestions was to use Charles Proxy, however I'm very new to how this works and am unable to figure it out. I've read through the Charles docs and spent a full day googling, but I can't find any info related to proxying between the NextJS API and Cloudinary SDK specifically.
How do I go about setting up Charles Proxy so that I can see the request and response in this way? Is there another way that I don't know of that would work instead? Since I'm using the newest version of NextJS v12, could I use the new _middleware option instead? In a later suggestion, their Support made this comment too:
if you can't proxy requests to localhost, you may be able to use a local DNS server or a local override so you can access your local IP using a different hostname (e.g. using /etc/hosts on a unix environment, or C:\Windows\System32\Drivers\etc\hosts on a windows PC) and have that proxied - that said, there's probably an easier way using a Node project or adjusting the settings of the Node server.
but I have no idea where to begin with this either.
Here is the api code I have:
pages/api/auth/images.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import cloudinary from 'cloudinary';
require('dotenv').config();
export default async function handler(_: NextApiRequest, res: NextApiResponse) {
cloudinary.v2.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
secure: true,
});
try {
// fetch cloudinary auth images
const response = await cloudinary.v2.api.resources({
type: 'upload',
prefix: 'my_app/auth_pages',
max_results: 20,
});
// fetch random image
const randImage =
response.resources[~~(response?.resources?.length * Math.random())];
// return image
return res.status(200).json({ image: randImage });
} catch (error) {
console.dir({ error }, { colors: true, depth: null });
return res.status(500).json({ error });
}
}
Note: I'm on a Mac.
Try the following:
export default async function handler(_: NextApiRequest, res: NextApiResponse) {
cloudinary.v2.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
api_proxy: 'http://<local_ip>:<charles_port>', //change accordingly
secure: true,
});
To get the port number, In Charles Proxy go to Proxy > Proxy Settings.
I want to create an API that can be called by the app itself (whether "ajax" or server-rendered) and other clients (e.g. mobile app). Most of the articles I found when googling "Quasar REST API" talk about how to access external APIs, which is not my case.
My understanding is to modify src-ssr/extension.js:
module.exports.extendApp = function({app, ssr}) {
app.get('/api/bla', (req, res) => {
res.send('something')
})
}
and ensure port inside src-ssr/index.js:
const ssr = require('../ssr'),
extension = require('./extension'),
app = express(),
port = process.env.PORT || 8888
matches the value in quasar.conf.js:
devServer: {
https: false,
open: false,
port: 8888,
},
The project builds and runs successfully, but http://localhost:8888/api/bla keeps loading in the browser. What do I miss?
I am new to Vue js and writing a front end for a simple task tracker app. I am trying to use vue-resource and http-proxy-middleware to have the app connect to my backend. Backend is on port 3000, and the Vue js front end is on port 8080.
I used the proxy set up described on the Vue docs.
The method:
saveTask() {
this.$http.get('/api', {title: this.taskTitle})
.then(response => {
console.log("success");
}, response => {
console.log("error");
});
}
My Proxy Table: (in config.index.js under dev)
proxyTable: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
When I start up the server I see:
[HPM] Proxy created: /api -> http://localhost:3000
[HPM] Proxy rewrite rule created: "^/api" ~> ""
> Starting dev server...
On the request:
GET http://localhost:8080/api 404 (Not Found)
So it looks like the proxy is not working. Any help greatly appreciated.
Your setup looks good and the requests should look like they're coming from 8080 since it is a proxy.
Are you sure something should be returning where you're looking? I have literally the same setup and it works.
My guess is since http://localhost:8080/api can't be found either can http://localhost:3000 since they're the same thing.
If that doesn't solve your problem you can dig a little deeper and debug and see if anything looks funny there.
proxyTable: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
logLevel: 'debug',
pathRewrite: {
'^/api': '',
},
},
},
Here goes a shot of everything working with my stuff:
what worked for me was setting up a vue.config.js file on the root dir of the vue project (that is at the same level that pacakge.json) and within that file I used this code:
module.exports = {
devServer: {
proxy: {
"^/api": {
target: "http://localhost:3000",
ws: true,
changeOrigin: true
}
}
}
}
now that the proxy was setup in the vue app the request would reach my express server :D
I'm trying to run express-stormpath on an aws linux instance that is successfully serving. I've double and tripled checked my keys and app hrefs and assured they were connected to applications. I've gone to a fresh vm and used the simplest service to ensure something wasn't awry in the VM where I am successfully serving a sailsjs app.
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
var stormpathInit = function(req,res,next) {
stormpath.init(app, {
apiKey: {
id:'##########',
secret: '############',
},
secretKey: 'theLongRoadToNowhere',
application: 'https://api.stormpath.com/v1/applications/###',
website: true,
api: true
});
next();
};
app.use(stormpathInit);
app.get('/', function (req, res) {
res.send('Login');
});
/* and this failed as well with the same output only on server startup
app.use(stormpath.init(app, {
apiKey: {
id:'4SL89BZ47ALZX6T9W7S4NPUXS',
secret: 's0dA33RPTAqcDAcdbwj6q9i0qDDEr0XyHhsBmjF34SY',
},
secretKey: 'theLongRoadToFreedomWillPayDividends',
application: 'https://api.stormpath.com/v1/applications/1wShCspJ1NFnT1N1UM1laJ',
website: true,
api: true
}));
*/
app.listen(1337);
///////////////////////
The error output:
req.uri = undefined
/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/ds/RequestExecutor.js:70
throw new Error('request.uri field is required.');
^
Error: request.uri field is required.
at RequestExecutor.executeRequest [as execute] (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/ds/RequestExecutor.js:70:13)
at doRequest (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/ds/DataStore.js:277:27)
at onCacheResult (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/ds/DataStore.js:301:5)
at Array.<anonymous> (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/cache/Cache.js:54:14)
at DisabledCache.get.DisabledCache.set.DisabledCache.delete.DisabledCache.clear.DisabledCache.size (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/cache/DisabledCache.js:11:62)
at Cache.get (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/cache/Cache.js:52:14)
at CacheHandler.getCachedResource [as get] (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/cache/CacheHandler.js:91:51)
at Object.executeRequest [as exec] (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/ds/DataStore.js:294:22)
at DataStore.getResource (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/ds/DataStore.js:122:16)
at Client.getResource (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/Client.js:313:38)
Any guidance is appreciated...
Unfortunately the answer from photon did not work for me, but after communicating with Stormpath support (which was very helpful) the following fixed my problem:
Set environment variable STORMPATH_APPLICATION_HREF by running this in the shell:
export STORMPATH_APPLICATION_HREF=<YourAppsHREF>
Hopefully this will work for others as well.
The problem seems to be a small typo in the stormpath documentation. They currently instruct you to set an environment variable called STORMPATH_CLIENT_APPLICATION_HREF. This is incorrect, it should be STORMPATH_APPLICATION_HREF as shown above.
I had the same problem and after looking at the current default options for the Stormpath middleware, changing the following line resolved my issue.
Before
application: 'https://api.stormpath.com/v1/applications/1wShCspJ1NFnT1N1UM1laJ'
After
application: {
href: 'https://api.stormpath.com/v1/applications/1wShCspJ1NFnT1N1UM1laJ'
}