Shared config file for both Angular and Node.js - node.js

I want to create a simple config file with one object, for example:
const config = {
serverIp: "localhost",
serverPort: 3000
}
which I can use in both Angular (Angular-cli with typescript):
import { config } from '../pathToConfigFile';
and node.js server (javascript):
const config = require("./config");
If I do this (config has .js extension):
export const config = {
ipOrDomainName: "localhost",
serverPort: 3000
}
if(module && module.exports){
module.exports = config;
}
I get this error on server
SyntaxError: Unexpected token export
And in typescript I get this error
Module '../../../../../config.js' was resolved to
'C:/Users/(...)/config.js', but '--allowJs'
is not set.
How can I get this module to be working in both Angular and node?

Related

Nuxt JS SSL Server Installation Problem on MacOS

Hello friends.
I need to continue my Nuxt JS work with SSL. However, after installation, I am getting the following error. I know the problem is because Node JS doesn't recognize the word "IMPORT". But I don't know how to solve the problem. Because I use Components as IMPORT all over the project. What is your suggestion?
Thank you very much in advance. 👋
package.json
"dev": "node server.js",
"nuxt": "^2.15.7",
"express": "^4.17.1"
ERROR IMAGE
error
SyntaxError: Cannot use import statement outside a module at compileFunction (<anonymous>)
nuxt.config.js
import axiosModule from './modules/axiosModule'
import momentModule from './modules/momentModule'
export default {
server: {
host: '0.0.0.0',
port: 3000,
},
......
server.js
const { Nuxt, Builder } = require('nuxt')
const expressServer = require('express')()
const thisHttp = require('http')
const thisHttps = require('https')
const thisFs = require('fs-extra')
const isProd = (process.env.NODE_ENV === 'production')
const isPort = 3000
let thisServer
if (isProd) {
const pKey = thisFs.readFileSync('./key.pem')
const pCert = thisFs.readFileSync('./cert.pem')
const httpsOptions = { key: pKey, cert: pCert }
thisServer = thisHttps.createServer(httpsOptions, expressServer)
} else {
thisServer = thisHttp.createServer(expressServer)
}
const nuxtConfig = require('./nuxt.config')
nuxtConfig.dev = !isProd
const nuxtServer = new Nuxt(nuxtConfig)
expressServer.use(nuxtServer.render)
const listen = () => { thisServer.listen(isPort, 'localhost') }
if (nuxtConfig.dev) {
new Builder(nuxtServer).build().then(listen()).catch(error => { console.log(error); process.exit(1) })
} else {
listen()
}
I fixed the situation manually. I did REQUIRE instead of IMPORT in Nuxt Config and used module.exports instead of Export Default. Even though I'm currently logging in via HTTPS, it's crossed out by Google Chrome.

Nuxt 6.14.6 redirect-ssl module not working into AWS

I am trying to configure redirect-ssl node module into nuxt application
Referece : https://www.npmjs.com/package/redirect-ssl
But when i load site in browser it gives me error with message -> Cannot GET /
ref. https://prnt.sc/xqsc05
Site works on SSL without redirect module. But I want to forcefully redirect all non HTTP request to HTTPS. I tried .htaccess code but I think nuxt do not supports it.
There is no error into terminal.
Tried following into nuxt.config.js different ways as following.
serverMiddleware: ["redirect-ssl"],
Into server/index.js file added following code
const redirectSSL = require('redirect-ssl')
async function start () {
.
.
app.use(redirectSSL)
}
How can we use .htaccess file into nuxt. I tried placing into root or nuxt project setup, but that did not worked for me.
Also anyone know how to implement CDN into nuxt other than build:publicPath variable.
Any help or suggestion for redirect-ssl module or nuxt with htaccess please ?
Try out following way.
Into server/index.js
const redirectSSL = require('redirect-ssl');
const fs = require("fs");
const path = require("path");
const https = require('https');
const express = require('express');
const consola = require('consola');
const { Nuxt, Builder } = require('nuxt');
const app = express()
const pkey = fs.readFileSync(path.resolve(__dirname, 'domain_ssl.com.key'));
const pcert = fs.readFileSync(path.resolve(__dirname, 'domain_ssl.com.crt'));
const httpsOptions = {
key: pkey,
cert: pcert
};
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = false
async function start () {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
await nuxt.ready()
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// nuxt render and middleware
app.use(nuxt.render)
app.use(redirectSSL.create({ redirectPort: 443 }))
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
https.createServer(httpsOptions,app).listen(443, host)
consola.ready({
message: `Server listening on https://${host}:${port}`,
badge: true
})
}
start()
Above one is for forcefully SSL redirection. And for CDN use this steps.
https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-build

How can i import additional files into server.js using sapper?

In my sapper app, i try to import a file into the server.js file like this:
import sirv from 'sirv';
import polka from 'polka';
import compression from 'compression';
import * as sapper from '#sapper/server';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const pushController = require('./backend/controllers/push');
polka()
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
sapper.middleware()
)
.post('/something/route', pushController.subscribe)
.listen(PORT, err => {
if (err) console.log('error', err);
});
But i always get the Error on console:
Error: Cannot find module './backend/controllers/push
my root folder looks like this:
- src
- backend
- controllers
- push.js
- client.js
- server.js
- service-worker.js
- template.html
I am using sapper with the default rollup config. Could the error therefore be related to rollup? How can I fix it?
A quick test shows it's ok with your structure. Please make sure you have
# push.js
function pushController() {
...
}
...
module.exports = { pushController }
and use import instead of require
# server.js
import { pushController } from './backend/controllers/push'

couchbase configuration cluster undefined

Using couchbase database, I get this error in config/db.js:
var cluster = new _couchbase2.default.Cluster(_env2.default.database.cluster);
TypeError: Cannot read property 'cluster' of undefined
config/env/development.js:
const config = {
database: {
cluster: '...',
password: '',
bucket: '...'
}
}
export default config;
config/env/index.js:
const env = process.env.NODE_ENV || 'development';
const config = require(`./${env}.js`);
export default config;
config/db.js:
import config from './env';
const cluster = new couchbase.Cluster(config.database.cluster);
Try importing couchbase into your file: config/db.js
import config from './env';
import couchbase from 'couchbase'
const cluster = new couchbase.Cluster(config.database.cluster);

Accessing NODE_ENV at runtime in the server.js configuration of Sails.js

I find myself not able to access the NODE_ENV variable when trying to make config changes in the config/server.js file of Sails.js. I want to configure the serverOptions flag of the express property and bind ssl certificates - but only for production.
Assuming I started the server with node app.js --prod
This doesn't work:
module.exports = { ... };
console.log(process.env.NODE_ENV); // undefined
But this does work:
module.exports = { ... };
setTimeout(function () {
console.log(process.env.NODE_ENV); // production
}, 1000);
Basically all I want to do is:
module.exports = (function () {
var env = process.env.NODE_ENV,
ret = { express: {} };
if (env == 'production') {
ret.express.serverOptions = { key: ..., cert: ... };
}
return ret;
}());
I've seen similar answers like https://stackoverflow.com/a/21152780/986408 but I can't understand how they should work when mine doesn't.
run your application like this instead:
NODE_ENV=production node app.js
or
sails lift --prod
in the application root directory. the command line switch you're trying to use is meant to be passed to the sails executable, not directly to your application javascript.

Resources