problem in set cookie and use proxy in vite react app - javascript

In Vite ReactJS Ts APP when try to set cookie and use proxy it's not working properly in production nut in the localhost it's working fine
that's my code at vite.config.ts
const defaultConfig = {
plugins: [
react({ include: "**/*.tsx", }),
],
server: {
proxy: {
'/api': {
target: 'https://tame-lime-rooster-tie.cyclic.app',
changeOrigin: true,
configure: (proxy, options) => {
proxy.on('proxyReq', (proxyReq, req, res) => {
if (!req.headers.cookie) {
return;
}
console.log('req.headers.cookie', req.headers.cookie)
proxyReq.setHeader('cookie', req.headers.cookie);
});
},
secure: false
}
}
}
}
export default defineConfig(({ command, mode }) => {
if (command === 'serve') {
const isDev = mode === 'development';
return {
...defaultConfig,
server: {
proxy: {
'/api': {
target: isDev ? 'http://localhost:5000' : 'https://tame-lime-rooster-tie.cyclic.app',
changeOrigin: true,
configure: (proxy, options) => {
proxy.on('proxyReq', (proxyReq, req, res) => {
if (!req.headers.cookie) {
return;
}
console.log('req.headers.cookie', req.headers.cookie)
proxyReq.setHeader('cookie', req.headers.cookie);
});
},
secure: false
}
}
}
}
} else {
return defaultConfig;
}
});
but it's working good only on localhost when i deploy the app it's not working good

Related

Webpack configuration for react-pdf in a Next.js project

Im using react-pdf library in Next.js to generate PDF, view PDF and download that PDF in a Static Client Side Next.js Application (Server is not involved). But I can't set up the Webpack for Next.js as I don't have much knowledge about it.
This is what the required setup for Webpack is for react-pdf:
const webpack = require('webpack')
module.exports = {
/* ... */
resolve: {
fallback: {
process: require.resolve('process/browser'),
zlib: require.resolve('browserify-zlib'),
stream: require.resolve('stream-browserify'),
util: require.resolve('util'),
buffer: require.resolve('buffer'),
asset: require.resolve('assert'),
},
},
plugins: [
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
process: 'process/browser',
}),
],
/* ... */
}
And this is the next.config.js:
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Important: return the modified config
return config
},
}
That config parameter that next.config.js gives us is like that objet we export in a normal webpack.config.js. Try with this setup of next.config.js:
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.resolve.fallback = {
process: require.resolve("process/browser"),
zlib: require.resolve("browserify-zlib"),
stream: require.resolve("stream-browserify"),
util: require.resolve("util"),
buffer: require.resolve("buffer"),
asset: require.resolve("assert"),
};
config.plugins.push(
new webpack.ProvidePlugin({
Buffer: ["buffer", "Buffer"],
process: "process/browser",
})
);
return config;
},
};
Try to place setupProxy.js file in src directory. It content
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app, req, res) {
const options = {
target: 'http://serverurl.com',
changeOrigin: true,
pathRewrite: function(path, req){
// console.log('path BEFORE trans: %o', path);
const p = path.replace('/api', '');
// console.log('current_path: %o', p);
// if(path.indexOf('manage') !== -1){
// p = '/web-module-backend'+p;
// }
// console.log('PATH: %o', p);
return p;
},
onProxyRes: (proxyRes, req, res) => {
// log original request and proxied request info
const exchange = `[${req.method}] [${proxyRes.statusCode}] ${req.path} -> ${proxyRes.req.protocol}//${proxyRes.req.host}${proxyRes.req.path}`;
// console.log(req.headers);
// console.log(proxyRes.headers);
console.log(exchange); // [GET] [200] / -> http://www.example.com
console.log('Req URL: ' + req.originalUrl);
console.log('Response status code: ' + proxyRes.statusCode);
res.headers = proxyRes.headers;
},
onProxyReq: (proxyReq, req, res) => {
Object.defineProperty(proxyReq, 'headers', {
get(){
return {
host: 'http://urlserver.com',
authorization: 'Authstring', // req.headers.authorization,
}
},
set(){
}
})
console.log(proxyReq.headers);
},
onError: (err, req, res, target) => {
console.log(err);
}
}
const uiProxy = createProxyMiddleware(options)
app.use(
'/api',
uiProxy
);
};

Why I'm getting status code 302 on query response?

Why I'm getting status code 302 on query response and how i can fix it?
fetch method:
const grabApps = async () => {
const res = await fetch(`${spinnakerURL}/gate/applications`, {
redirect: "manual"
})
return res.data || []
}
vue.config.js
module.exports = {
devServer:
{
proxy:
{
'/gate':
{
target: 'https://spinstatus.zenoss.io',
changeOrigin: true,
onProxyReq: (proxyReq, req, res, options) =>
{
proxyReq.setHeader('Origin', 'https://spinstatus.zenoss.io')
}
}
}
}
}

Cookie problem with node/apollo/express server after deploying to Heroku

I'm building node js server with apollo and front end with next.js/apollo client. My problem is that on localhost everything is works as it must be, but after deploying to Heroku cookies not set. I'm getting the data from server and redirects me to the home page, but after page reload it redirects me to login page again.
This is apollo server code
import cors from 'cors'
import Redis from 'ioredis'
import dotenv from 'dotenv'
import express from 'express'
import mongoose from 'mongoose'
import session from 'express-session'
import connectRedis from 'connect-redis'
import { ApolloServer } from 'apollo-server-express'
import typeDefs from './schema'
import resolvers from './resolvers'
dotenv.config({
path: `.env.${process.env.NODE_ENV}`,
})
const port = process.env.PORT || 4000
const dev = process.env.NODE_ENV !== 'production'
const RedisStore = connectRedis(session)
const startServer = async () => {
await mongoose
.connect(process.env.DB_URL, { useNewUrlParser: true })
.then(() => console.log(`🔗 MongoDB Connected...`))
.catch(err => console.log(`❌ MongoDB Connection error: ${err}`))
const app = express()
const server = new ApolloServer({
typeDefs,
resolvers,
playground: !dev
? false
: {
settings: {
'request.credentials': 'include',
},
},
context: ({ req, res }) => ({ req, res }),
})
app.disable('x-powered-by')
app.set('trust proxy', 1)
app.use(
cors({
credentials: true,
origin:
process.env.NODE_ENV === 'production'
? process.env.FRONT_END_URL
: 'http://localhost:3000',
}),
)
app.use((req, _, next) => {
const authorization = req.headers.authorization
if (authorization) {
try {
const cid = authorization.split(' ')[1]
req.headers.cookie = `cid=${cid}`
console.log(cid)
} catch (err) {
console.log(err)
}
}
return next()
})
app.use(
session({
store: new RedisStore({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
pass: process.env.REDIS_PASS,
}),
name: process.env.SESS_NAME,
secret: process.env.SESS_SECRET,
saveUninitialized: false,
resave: false,
cookie: {
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days
secure: false,
},
}),
)
server.applyMiddleware({ app, cors: false })
app.listen({ port }, () =>
console.log(
`🚀 Server ready at http://localhost:${port}${server.graphqlPath}`,
),
)
}
startServer()
and this is the resolvers
import gravatar from 'gravatar'
import bcrypt from 'bcrypt'
import { User } from '../models'
import { isAuthenticated, signOut } from '../auth'
import { loginSchema, registerSchema } from '../utils'
export default {
Query: {
users: (parent, args, { req }, info) => {
isAuthenticated(req)
return User.find({})
},
user: (parent, { id }, context, info) => {
isAuthenticated(req)
return User.findById(id)
},
me: (parent, args, { req }, info) => {
isAuthenticated(req)
return User.findById(req.session.userId)
},
},
Mutation: {
signUp: async (parent, args, { req }, info) => {
// isAuthenticated(req)
args.email = args.email.toLowerCase()
try {
await registerSchema.validate(args, { abortEarly: false })
} catch (err) {
return err
}
args.avatar = await gravatar.url(
args.email,
{
protocol: 'https',
s: '200', // Size
r: 'pg', // Rating
d: 'mm', // Default
},
true,
)
args.password = await bcrypt.hash(args.password, 12)
const user = await User.create(args)
req.session.userId = user.id
return user
},
signIn: async (parent, args, { req }, info) => {
// isAuthenticated(req)
const { email, password } = args
try {
await loginSchema.validate(args, { abortEarly: false })
} catch (err) {
return err
}
const user = await User.findOne({ email })
if (!user || !(await bcrypt.compare(password, user.password))) {
throw new Error('Incorrect email or password. Please try again.')
}
req.session.userId = user.id
return user
},
signOut: (parent, args, { req, res }, info) => {
return signOut(req, res)
},
},
}
and here is apollo client on front end (I'm using with-apollo-auth example from next.js)
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { createHttpLink } from 'apollo-link-http'
import { setContext } from 'apollo-link-context'
import fetch from 'isomorphic-unfetch'
let apolloClient = null
if (!process.browser) {
global.fetch = fetch
}
function create(initialState, { getToken }) {
const httpLink = createHttpLink({
uri:
process.env.NODE_ENV === 'development'
? 'http://localhost:4000/graphql'
: process.env.BACK_END_URL,
credentials: 'include',
})
const authLink = setContext((_, { headers }) => {
const token = getToken()
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
}
})
return new ApolloClient({
connectToDevTools: process.browser,
ssrMode: !process.browser,
link: authLink.concat(httpLink),
cache: new InMemoryCache().restore(initialState || {}),
})
}
export default function initApollo(initialState, options) {
if (!process.browser) {
return create(initialState, options)
}
if (!apolloClient) {
apolloClient = create(initialState, options)
}
return apolloClient
}
Thanks in advance.

electron how to redirect data from node to angular 7

I generated an Angular 7 application, which is running at http://localhost:4200
I have an application in Node JS that is responsible for authenticating the user on Facebook, running at http://localhost:3000
there the callback redirection works correctly
index.js (node)
//facebook
const FACEBOOK_APP_ID = 'xxx';
const FACEBOOK_APP_SECRET = 'xxx';
passport.use(new FacebookStrategy({
clientID: FACEBOOK_APP_ID,
clientSecret: FACEBOOK_APP_SECRET,
callbackURL: "/auth/facebook/callback"
},
function (accessToken, refreshToken, profile, cb) {
return cb(null, profile, accessToken);
}
));
app.get('/auth/facebook',
passport.authenticate('facebook'));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
failureRedirect: 'http://localhost:4200/login'
}),
function (req, res) {
res.redirect('http://localhost:4200/main' + req.authInfo);
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`server en port ${port}`)
});
app.modules.ts
const appRoutes: Routes = [{
path: '',
component: LoginComponent,
},
{
path: 'login',
component: LoginComponent,
},
{
path: 'main/:token',
component: MainComponent,
},
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: '**',
component: Error404Component
},
];
main.js (electron)
const url = require('url');
const path = require('path');
const fs = require('fs');
const {
app,
BrowserWindow,
Menu,
dialog
} = require('electron');
const openAboutWindow = require('about-window').default;
let win;
let menu;
const application_menu = [{
label: 'Archivo',
submenu: [{
label: 'Salir',
accelerator: 'Command+Q',
click: () => {
app.quit();
}
}, ]
},
{
label: 'Configuración',
submenu: [{
label: 'Carpetas',
accelerator: 'CommandOrControl+o',
click: () => {
openFolderDialog()
}
}]
},
{
label: 'Ayuda',
submenu: [{
label: 'Documentación',
click() {
require('electron').shell.openExternal('https://electronjs.org')
}
},
]
}
];
function createWindow() {
let nd = require('./api/index.js');
menu = Menu.buildFromTemplate(application_menu);
Menu.setApplicationMenu(menu);
win = new BrowserWindow({
width: 800,
height: 600,
show: false,
icon: __dirname + '/icons/batman.ico'
});
win.loadFile('./dist/UI/index.html');
win.webContents.openDevTools()
win.once('ready-to-show', () => {
win.show()
})
win.on('closed', function () {
win = null;
});
};
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
});
app.on('activate', () => {
if (win === null) {
createWindow()
}
});
When trying to include it in Electron, I can invoke the node functions, but I can not redirect the data to angular
I tried with file: /// and it does not work either, it does not give error either
I appreciate your help
I think you must return JSON response and make decision in electron app based on JSON , whether the authorization has passed or not. Because the starting point of the angular and that serves it is electron app, and i think you can't redirect this way.

Node hapi app starts, but doesnt appear to bind to port

I have an hapi app that is in development. Upon running my usual node-foreman with Procfile, the app loads in the command line with no errors, but upon browsing to the configured port, the page errors, no connection, or specifically, connection refused. Back to the CLI, no errors. simple message from the server.start "Server running on http://localhost:3000"
I tried directly launching with gulp (no errors). No browser access.
I tried directly launching with node (no errors). No browser access.
I tried creating a hello world app with hapi, and express, both had no errors and DID load in the browser.
I even version controlled the code back to a version I know worked. Starts server fine from CLI, but no browser loading/access.
I'm a little stuck, would love any thoughts on even a path to go down to trouble shoot.
Thank you in advance.
Here is the app JS:
var config = require('./config');
hapi = require('../lib/hapi'),
chalk = require('chalk'),
module.exports.init = function (callback) {
//init app bserver
server = hapi.init();
callback(server, config );
};
module.exports.start = function (callback) {
var _this = this;
_this.init(function (server, config) {
// Start the app by listening on <port>
server.start(function () {
// Logging initialization
console.log('+-----------------------------------------------------------+');
console.log(chalk.green('| ' + config.app.title+ '\t\t\t|'));
console.log('+-----------------------------------------------------------+');
console.log(chalk.green('| Environment:\t' + process.env.NODE_ENV));
console.log(chalk.green('| Standard Port:\t' + config.port));
if (config.https.ssl === true ) {
console.log(chalk.green('| Secure Port:\t' + config.https.port));
console.log(chalk.green('| HTTPs:\t\ton'));
}
console.log(chalk.green('| App version:\t' + config.version));
console.log(chalk.green('| App url:\t\t' + ((config.https.ssl === true ? 'https' : 'http')+"://"+config.url)));
console.log('+-----------------------------------------------------------+');
console.log('| Database Configuration\t\t\t\t\t|');
console.log('+-----------------------------------------------------------+');
console.log(chalk.green(JSON.stringify(config.db, null, 4)));
console.log('+-----------------------------------------------------------+');
if (callback) callback(server, db, config);
});
return server;
});
};
AND HERE IS THE HAPI INCLUDE:
var config = require('../general/config'),
Hapi = require('hapi'),
Good = require('good'),
Hoek = require('hoek'),
Inert = require('inert'),
Vision = require('vision'),
Path = require('path'),
Boom = require('boom'),
Bell = require('bell'),
Cookie = require('hapi-auth-cookie'),
Url = require('url'),
hapiAuthSessions = require('./sessions'),
Promise = require('bluebird'),
fs = require('fs');
/* Initialize ORM and all models */
module.exports.initDBConnections = function( server ) {
server.register([
{
register: require('hapi-sequelize'),
options: [
{
sequelize: new Sequelize(process.env.DATABASE_URL),
name: config.db.connection.database,
models: config.files.server.models,
sync: true,
forceSync:false
}
]
}
], function(err) {
Hoek.assert(!err, err);
});
}
/**
* Initialize rendering engine
*/
module.exports.initRenderingEngine = function (server) {
var paths = [];
var layouts = [];
var partials = [];
var helpers = [];
/* add each module paths to rendering search, assume if route, there is a view fr module */
config.files.server.routes.forEach(function (routePath) {
var rp = Path.relative(Path.join(__dirname,'../../'),Path.resolve(Path.dirname(routePath)+'/../../'))
if(fs.existsSync(rp+'/server/views/'+config.theme+'/content'))
paths.push(rp+'/server/views/'+config.theme+'/content');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/errors'))
paths.push(rp+'/server/views/'+config.theme+'/errors');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/layouts'))
layouts.push(rp+'/server/views/'+config.theme+'/layouts');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/partials'))
partials.push(rp+'/server/views/'+config.theme+'/partials');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/helpers'))
helpers.push(rp+'/server/views/'+config.theme+'/helpers');
});
server.views({
engines: {
html: require('handlebars')
},
path: paths,
layoutPath: layouts,
partialsPath: partials,
helpersPath: helpers,
layout: 'base.view'
});
}
/**
* Initialize local variables
*/
module.exports.initLocalVariables = function (server) {
// Setting application local variables
for (var property in config) {
if (config.hasOwnProperty(property)) {
if (!server.app[property]) {
server.app[property] = config.app[property]
}
}
}
};
/**
* Initialize static routes for browser assets
*/
module.exports.initStaticRoutes = function (server) {
server.route([{
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: Path.join(__dirname, '../../public'),
redirectToSlash: true,
listing: false,
defaultExtension: 'html'
}
}
},{
method: 'GET',
path: '/assets/vendor/{param*}',
handler: {
directory: {
path: Path.join(__dirname, '../../node_modules'),
redirectToSlash: false,
listing: false,
defaultExtension: 'js'
}
}
}]);
}
/**
* Initialize server logging
*/
module.exports.initLogging = function (server) {
return {
ops: {
interval: 1000
},
reporters: {
myConsoleReporter: [{
module: 'good-squeeze',
name: 'Squeeze',
args: [{ log: '*', response: '*' }]
}, {
module: 'good-console'
}, 'stdout']
}
};
}
/**
* Initialize App Tenant
*/
module.exports.initAppTenant = function (server) {
server.ext('onRequest', function (req, res) {
server.app['tenant'] = req.info.hostname;
res.continue();
});
};
/**
* Initialize ensure SSL
*/
module.exports.initSSL = function(server) {
server.select('http').route({
method: '*',
path: '/{p*}',
handler: function (req, res) {
// redirect all http traffic to https
console.log('redirecting',config.url + req.url.path);
return res.redirect('https://' + config.url + req.url.path).code(301);
},
config: {
description: 'Http catch route. Will redirect every http call to https'
}
});
}
/**
* Initialize static routes for modules in development mode browser assets
*/
module.exports.initModulesStaticRoutes = function(server) {
if (process.env.NODE_ENV === 'development') {
server.route({
method: 'GET',
path: '/modules/{param*}',
handler: {
directory: {
path: Path.join(__dirname, '../../modules'),
redirectToSlash: false,
listing: false,
defaultExtension: 'html'
}
}
});
}
}
/**
* Configure the modules server routes
*/
module.exports.initModulesServerConfigs = function (server) {
config.files.server.configs.forEach(function (routePath) {
require(Path.resolve(routePath))(server);
});
};
/**
* Configure the modules server routes
*/
module.exports.initModulesServerRoutes = function (server) {
config.files.server.routes.forEach(function (routePath) {
require(Path.resolve(routePath))(server);
});
};
/**
* Configure Socket.io
*/
module.exports.configureSocketIO = function (server) {
// Load the Socket.io configuration
var server = require('./socket.io')(server);
// Return server object
return server;
};
/**
* Initialize hapi
*/
module.exports.init = function init() {
var server = new Hapi.Server({
connections: {
routes: {
files: {
relativeTo: Path.join(__dirname, 'public')
}
},
state: {
isSameSite: 'Lax'
}
},
debug: {
'request': ['error', 'uncaught','all','request']
},
cache: [
{
name: 'cacheMem',
engine: require('catbox-memcached'),
host: '127.0.0.1',
port: '8000',
partition: 'cache'
},{
name : 'cacheDisk',
engine : require('catbox-disk'),
cachePath: '/var/tmp',
partition : 'cache'
}
]
});
server.connection({
labels: 'http',
port: config.port
});
if(config.https.ssl == true) {
server.connection({
labels: 'https',
port: config.https.port,
tls: {
key: config.https.key,
cert: config.https.cert
}
});
/* redirect ssl */
this.initSSL(server);
}
server.register([Vision,{register: Good, options: this.initLogging(server)},Cookie,Bell,Inert], function(err) {
Hoek.assert(!err, err);
var _this = module.exports;
var _thisServer = server.select((config.https.ssl == true ? 'https' : 'http'));
/* Initialize sessions */
hapiAuthSessions._init(_thisServer);
/* detect app tenant */
_this.initAppTenant(_thisServer);
/* app local variables */
_this.initLocalVariables(_thisServer);
/* logging */
_this.initLogging(_thisServer);
/* static file serving */
_this.initStaticRoutes(_thisServer);
/* module config, routes, static routes */
_this.initModulesStaticRoutes(_thisServer);
_this.initModulesServerConfigs(_thisServer);
_this.initModulesServerRoutes(_thisServer);
/* rendering engine */
_this.initRenderingEngine(_thisServer);
// Configure Socket.io
server = _this.configureSocketIO(_thisServer);
//server.start located in ../general/app.js
});
return server;
}
HERE IS THE CLI OUTPUT:
[13:58:31] [nodemon] starting `node --inspect server.js`
[13:58:31] [nodemon] child pid: 5596
Debugger listening on ws://127.0.0.1:9229/e2f5837f-b552-4156-b004-e7adb3d30d05
For help see https://nodejs.org/en/docs/inspector
+-----------------------------------------------------------+
| APP - Development Environment |
+-----------------------------------------------------------+
| Environment: development
| Standard Port: 3000
| Secure Port: 3001
| HTTPs: on
| App version: 0.3.0
| App url: https://localhost:3001
+-----------------------------------------------------------+
| Database Configuration |
+-----------------------------------------------------------+
{
"client": "postgresql",
"connection": {
"host": "localhost",
"port": "5432",
"database": "database",
"user": "user",
"password": "password",
"ssl": true
},
"pool": {
"min": 2,
"max": 10
},
"migrations": {
"tableName": "knex_migrations"
},
"debug": true
}
+-----------------------------------------------------------+
Ok. I found the answer (this is twice in a week over looking small detail -- Shame on me).
The smaller problem, that lead me to the larger problem, was upon server.start(callback) I didn't have any error checking, similar to:
server.start(function(err) {
if(err) {
throw err;
}
});
Once I added the err logging, it exposed the reason the server was quietly failing.
My Hapi config was requiring a memcached module, and I had not started my memcached server locally.
All back to to working as designed :)

Categories

Resources