Because of the Access to XMLHttpRequest CORS policy I've had to create a proxy in my package.json folder to get around posting to an external API. However, when trying to deploy this to Heroku I am getting: Invalid Host header. I've setHOST=name.herokuapp.com in my .env.production as well as tried using middleware:
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
createProxyMiddleware(
["external_api/endurl"],
{
target: "externalapi/starturl",
}
)
);
};
Related
I am new to Nuxt3. I tried to connect my Nuxt3 app to my backend site which is built with Laravel. My frontend URL is http://localhost:3000 and my backend is http://localhost:8000. When I connect to http://localhost:8000/api/names using "useFetch" inside a component, it runs fine. But when I do it inside server/api/names.js using $fetch, it shows a 500 (Internal server error).
This runs fine (sample.vue)
const getNames = async () => {
let { data } = await useFetch('http://localhost:8000/api/names')
console.log(data);
}
This does not
(sample.vue)
const getNames = async () => {
let { data } = await useFetch('/api/names')
console.log(data);
}
(/server/api/names.js)
export default defineEventHandler(async (event) => {
const { data } = await $fetch("http://localhost:8000/api/names");
return { data };
});
Here's the code on my Laravel app inside api.php (http://localhost:8000/api/names)
Route::get('/names', function (){
$users_name = User::all()->pluck('name');
return response()->json(['names' => $users_name]);
});
Here's the error that shows when I go to network tab
message: "terminated"
stack: "<pre><span class=\"stack internal\">at Fetch.onAborted (node:internal/deps/undici/undici:11000:53)</span>\n<span class=\"stack\">at Fetch.emit (node:events:513:28)</span>\n<span class=\"stack internal\">at Fetch.terminate (node:internal/deps/undici/undici:10272:14)</span>\n<span class=\"stack internal\">at Object.onError (node:internal/deps/undici/undici:11095:36)</span>\n<span class=\"stack internal\">at Request.onError (node:internal/deps/undici/undici:6477:31)</span>\n<span class=\"stack internal\">at errorRequest (node:internal/deps/undici/undici:8440:17)</span>\n<span class=\"stack internal\">at Socket.onSocketClose (node:internal/deps/undici/undici:7895:9)</span>\n<span class=\"stack\">at Socket.emit (node:events:513:28)</span>\n<span class=\"stack\">at TCP.<anonymous> (node:net:313:12)</span></pre>"
statusCode: 500
statusMessage: ""
url: "/api/names"
I tried to restart both servers hoping that doing this would fix the issue but the problem still persists. Also searched if it has something to do with CORS but it connects when I call the api inside a component.
I had exactly the same problem yesterday and luckily I found a solution without having to downgrade the version of NodeJS because Nuxt3 does not work well under version 16 of Node.
First use Laragon for your Laravel Backend. Laragon automatically creates Hostname for projects ex: laravelbackend.test if the project folder is called "laravelbackend".
Then on the file (/server/api/names.js) replace localhost:8000/api with laravelbackend.test/api
export default defineEventHandler(async (event) => {
const { data } = await $fetch("http://laravelbackend.test/api/names");
return { data };
});
Strapi Error
I am trying to deploy a Strapi app to Heroku. I have set APP_KEYS and JWT_SECRET config vars in Heroku. I have also added this code to plugins.js as stated in this question. But I am still getting this error (see image). Can anyone help with this?
const crypto = require("crypto");
module.exports = ({ env }) => ({
"users-permissions": {
config: {
jwtSecret: env("JWT_SECRET") || crypto.randomBytes(16).toString("base64"),
},
},
});
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'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'
}