Localhost refuses to connect when I make setupProxy.js - javascript

I made my setupProxy.js to deal with a CORS issue:
const proxy = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
proxy('/myUrl', {
target: 'http://localhost:8090',
changeOrigin: true
})
)
};
After I made it and run 'npm start' again, my browser says that localhost refuses to connect. If I delete setupProxy.js, I can connect to localhost, but the CORS policy blocks to connect with backend server.
Do you have any idea to connect to frontend, still using the setupProxy.js?

You can try this: createProxyMiddleware
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
createProxyMiddleware('/myUrl', {
target: 'http://localhost:8090',
changeOrigin: true,
})
);
};
https://stackoverflow.com/a/60354374/11652543

See that you have spelled the name of setupProxy.js well that solved the problem for me. If that does not work. Copy and pase the fb's code the way it is into the setupProxy.js Code can be found here

Related

Nuxt - server middleware not working on production

I have builded an app using Nuxt and I have created simply server middleware for handling email sending. Everything is working on dev but on production I have 404 error from that endpoint. Does anybody know how to include server-middleware into build files or any other way?
server-middleware:
const bodyParser = require('body-parser')
const app = require('express')()
app.use(bodyParser.json())
app.post('/', (req, res) => {
// Some code here
})
module.exports = app
Nuxt.config.js
serverMiddleware: [
{ path: '/contact/send', handler: '~/server-middleware/email.js' }
],
Response here:
I found an answer on github issue nuxt repo:
This is correct - server middleware aren't compiled or part of your
webpack build and so you should make sure to copy them separately into
production. (As well as making sure that any dependencies they have
are installed in production.)
(Note that this will change with Nuxt 3 - you'll be able to have a
single built server that includes your server middleware.)
Issue here:
https://github.com/nuxt/nuxt.js/issues/9158#issuecomment-820676790
Here is an in-depth answer regarding the whole setup of a serverMiddleware.
This solutions seems to work: https://github.com/nuxt/nuxt.js/issues/1486#issuecomment-325181524
// nuxt.config.js
serverMiddleware: [
'~/api/index.js',
]
// api/index.js
const app = require('express')()
module.exports = { path: '/api', handler: app }
app.get('/say/:word', (req, res) => {
res.json(req.params)
})

How to Set up Vue CORS for different domain API?

I' trying to deploy an Vue app which has a separate backend and which will be hosted in different domain. For example:
meow.cat.xyz (App)
api.meow.cat.xyz (API)
Now after npm run build I tried to preview it locally by running serve -s dist and the application is severing at localhost:5000. However the problem is it not sending API request at the current end point (which is localhost:8000 at local and api.meow.cat.xyz at server). I tried config CORS as following
vue.config.js
module.exports = {
devServer: {
port: process.env.VUE_APP_DEV_PORT,
proxy: process.env.VUE_APP_API_ROOT_PATH,
},
};
.env.development
VUE_APP_API_ROOT_PATH = 'http://localhost:8000/api'
VUE_APP_DEV_PORT = 3000
Note that I'm using axiox. Here is my axios setup.
API.js
import axios from "axios";
const injectAccessToken = (config) => {
const accessToken = localStorage.getItem("access_token");
if (accessToken)
config.headers.common["Authorization"] = `Bearer ${accessToken}`;
return config;
};
const config = {
baseURL: process.env.VUE_APP_API_ROOT_PATH,
};
const API = axios.create(config);
API.interceptors.request.use(injectAccessToken);
export default API;
and Using it as following
Login.vue
import API from "#/api/Api";
<script>
const res= await API.post('login')
</script>
This solution is not working yet. Its sending request at http://localhost:5000. What's the point ? Note that I'm using axios. thanks in advance.
Allow CORS requests from the server
With the Access-Control-Allow-Origin header, you can specify what origins can use your API.
app.get('/api', (req, res) => {
res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
res.send({
api: "your request."
});
})
Allow CORS from the app's origin on the server (api).
This has nothing to do with with the client (app)

Does log4js require any extra code to work on an Apache server?

I'm trying to add Log4js-Node to a Node.js server running on Apache. Here's my code:
const path = require("path");
const express = require("express");
const log4js = require('log4js');
const app = express();
const logger = log4js.getLogger();
logger.level = "debug";
const port = 443;
log4js.configure({
appenders: { everything: { type: 'file', filename: 'logs.log', flags: 'w' } },
categories: { default: { appenders: ['everything'], level: 'ALL' } }
});
const server = app.listen(port, () => {
logger.debug("listening to requests on port " + port);
});
app.get("/log", (req, res) => {
res.sendFile(path.join(__dirname + "/logs.log"));
});
When I run the script on Node.js on my computer and navigate to localhost:443/log I see what I expect, which is this:
[2020-03-17T22:50:43.145] [DEBUG] default - listening to requests on port 443
But when I run the code on a remote server it crashes and I get this in the error page (with part of the path replaced by me with "[removed]"):
App 25925 output: at Server. ([removed]/index.js:27:9)
App 25925 output: at Logger. [as debug] ([removed]/12/lib/node_modules/log4js/lib/logger.js:124:10)
App 25925 output: at Logger.log ([removed]/12/lib/node_modules/log4js/lib/logger.js:73:12)
App 25925 output: at Logger._log ([removed]/12/lib/node_modules/log4js/lib/logger.js:90:16)
App 25925 output: at Object.send ([removed]/12/lib/node_modules/log4js/lib/clustering.js:97:15)
App 25925 output: [removed]/12/lib/node_modules/log4js/lib/clustering.js:97
App 25925 output: at Object. ([removed]/12/lib/node_modules/log4js/lib/clustering.js:8:13)
I'm using A2 Hosting which uses Apache 2.4.41. I opted for Node.js 12.9.0, and Log4js 6.1.2. The package.json should be the same on both my computer and the server, and I've run npm install on both.
Is this just an issue with Log4js and the server, or have I missed something somewhere?
This was actually a relatively simple fix. The path referenced by the last error in the stack trace is a Log4js module that implements clustering support through Node's "cluster" module. The line "8" referenced is cluster = require("cluster"). It's wrapped in a try/catch block like this:
try {
cluster = require("cluster"); //eslint-disable-line
} catch (e) {
debug("cluster module not present");
disabled = true;
}
The installation of Node.js on my computer came with the "cluster" module, however as far as I can tell, the server I'm using doesn't support it. Also, the version of Node I'm using on my computer is newer than what I'm using on the server (so I've now installed 12.9 on my machine). I believe the older version of Node doesn't bother trying to catch the exception and tries to load the cluster module, fails, and then throws the error.
So the simple fix was to comment out most of the "try/catch" block, leaving just the contents of "catch" like this:
// try {
// cluster = require("cluster"); //eslint-disable-line
// } catch (e) {
debug("cluster module not present");
disabled = true;
// }
If someone has a better fix, I'm open to suggestions.
The same response of #skittleswrapper,thx, it work for me.
I use Node.js 14.18.1 with log4js 6.3.0.
But i wondering what'is the necessary of this module 'cluster' and if we can
add it to our app in other way.

How to configure a proxy like in CRA without create-react-app?

In a create-react-app, I can use proxy in package.json to configure a proxy automatically, as described in here https://create-react-app.dev/docs/proxying-api-requests-in-development/
This allow me to serv my app from a different port.
How can I do the same configuration without create-react-app?
It would be nice to have the same proxy to benefit the same configuration as in with create-react-app.
You can create a file to run with node to act as your proxy. Like this:
proxy.js
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({
secure: false,
changeOrigin: true,
target: 'https://someOriginURL.com',
// could be an IP address target: 'https://XX.XX.XXX.XXX/',
}).listen(3500, () => console.log('Proxy running on port 3500'));
// Intercepts the request
proxy.on('proxyReq', function(proxyReq, req, res, options) {
console.log(req);
// Set the headers of the intercepted request
proxyReq.setHeader('Origin', 'https://yourorigin.com');
// remove any headers you want
// proxyReq.removeHeader('authorization');
res.oldWriteHead = res.writeHead;
res.writeHead = function(statusCode, headers) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.oldWriteHead(statusCode, headers);
}
});
to use this open a terminal and run:
node proxy.js
P.S.: Don't use this in production :D

Firebase cloud functions work locally but not after deployment

I'm currently attempting to deploy a Nuxt SSR app to Firebase.
Everything works correctly on local and the firebase server. The cloud function correctly executes and renders the html, no problem.
The problem happens when I add a request to and external API (Storyblok). I'm on the Blaze plan so external requests should work, right?
Everything works on local using the cloud functions emulator and through firebase serve --only functions,hosting with the external API request but I get an error 500 after deploying.
Is there a way to get a more detailed log of what may be happening on the Firbase end?
Cloud Function:
const functions = require('firebase-functions');
const { Nuxt } = require('nuxt');
const express = require('express');
const app = express();
const config = {
dev: false,
buildDir: 'nuxt',
build: {
publicPath: '/assets/'
}
}
const nuxt = new Nuxt(config);
function handleRequest(req, res) {
res.set('Cache-Control', 'public, max-age=150, s-maxage=150');
return new Promise((resolve, reject) => {
nuxt.render(req, res, promise => {
promise.then(resolve).catch(reject)
})
});
}
app.use(handleRequest);
exports.nuxtssr = functions.https.onRequest(app);
Try to add debug: true in your Nuxt config.
i.e.
const config = {
debug: true,
dev: false,
buildDir: 'nuxt',
build: {
publicPath: '/assets/'
}
}
This will make the error message shows in browser, instead of just error 500.
Referring you to :
https://firebase.google.com/docs/functions/writing-and-viewing-logs#viewing_logs
perhaps this would have more details using Using the Firebase CLI.

Categories

Resources