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'
Related
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.
ESLint has me second-guessing myself today. I am building a simple Express application and it's yelling because I am importing DevDependencies in my app.ts file (yes, I am using Typescript). Basically I want my app to use the npm packages dotenv and morgan only when in development. In production, I will not need either of these packages. So what is the proper way to include these in my project?
Here is my current setup:
Basic app.ts file:
import express from 'express';
import morgan from 'morgan';
import dotenv from 'dotenv';
import helmet from 'helmet';
import compression from 'compression';
import cookieParser from 'cookie-parser';
import https from 'https';
import path from 'path';
import fs from 'fs';
import logger, { stream } from './util/logger';
/**
* Express Application Class
*/
class App {
public app: express.Application;
public port: number;
constructor(port: number) {
this.app = express();
this.port = port;
this.registerMiddleware();
}
/**
* Registers middleware for use
*/
private registerMiddleware(): void {
/** Use dotenv for development env variables */
if (process.env.NODE_ENV !== 'production') {
dotenv.config();
this.app.use(morgan('dev', { stream }));
}
this.app.use(helmet());
this.app.use(compression());
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: false }));
this.app.use(cookieParser());
}
/**
* Starts the Express.js server.
*/
public start(): void {
this.app.listen(this.port, () => {
logger.info(`Server started at https://localhost:${this.port}`);
});
}
/**
* Starts the secure Express.js server.
*/
public startDev(): void {
/** Start a secure Express server for local testing */
https
.createServer(
{
key: fs.readFileSync(path.resolve('server.key')),
cert: fs.readFileSync(path.resolve('server.crt')),
},
this.app
)
.listen(3000, () => {
logger.info(`Secure server started at https://localhost:${this.port}`);
});
}
}
export default App;
Basic server.ts file:
import App from './app';
/**
* Init Express.js server.
*/
const server = new App(3000);
/**
* Start Express.js server.
*/
if (process.env.NODE_ENV !== 'production') {
server.startDev();
} else {
server.start();
}
you can save them as optional dependencies other than dev dependencies using
npm install dotenv morgan --save-optional
Reference
I have a troubles with express.js it's trying to use ssl3 but I didn't use it anywhere. I see next error then running the server:
(node:7920) [DEP0026] DeprecationWarning: util.print is deprecated.
Use console.log instead. Error: 4776:error:1408F10B:SSL
routines:ssl3_get_record:wrong version
number:openssl\ssl\record\ssl3_record.c:252:
The server.js file looks like this:
// import npm modules
import fs from 'fs';
import path from 'path';
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import winston from 'winston';
import compression from 'compression';
import expressWinston from 'express-winston';
import winstonPapertrail from 'winston-papertrail';
import jwt from 'express-jwt';
import http from 'http';
// import custom configuration and utilities
import config from './config';
import logger from './utils/logger';
import db from './utils/db';
import routes from './routes';
// initialize the api
const api = express();
// initialize middleware
api.use(cors());
api.use(compression());
api.use(bodyParser.urlencoded({ extended: true }));
api.use(bodyParser.json());
// ignore authentication on the following routes
api.use(
jwt({ secret: config.jwt.secret }).unless({
path: [
'/',
'/auth/signup',
'/auth/login',
'/auth/forgot-password',
'/auth/reset-password',
],
}),
);
// throw an error if a jwt is not passed in the request
api.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
res.status(401).send('Missing authentication credentials.');
}
});
// initialize our logger (in our case, winston + papertrail)
api.use(
expressWinston.logger({
transports: [
new winston.transports.Papertrail({
host: config.logger.host,
port: config.logger.port,
level: 'error',
}),
],
meta: true,
}),
);
// listen on the designated port found in the configuration
api.listen(config.server.port, err => {
if (err) {
logger.error(err);
process.exit(1);
}
// require the database library (which instantiates a connection to mongodb)
db();
// loop through all routes and dynamically require them – passing api
Object.entries(routes).forEach(([ key, route ]) => {
route(api);
});
// output the status of the api in the terminal
logger.info(`API is now running on port ${config.server.port} in ${config.env} mode`);
});
export default api;
├───dist
└───src
├───config
├───controllers
├───models
├───routes
└───utils
How can I solve this problem? I wont use ssl right now. Thanks
I have a react app, which uses a router and works fine if the URL is not entered directly into the address bar, but rather is set by react router when navigating the app. I have added ExpressJS to the app, by running the react app via the Express proxy. The goal is to re-direct any dynamic requests to the react app, so that it can handle it, instead of Express. I have looked at many examples and tried using them, but I had no luck in making the re-direct work.
The folder structure and key file locations are as follows:
[Root directory]
---- [client]
--------- [node_modules]
--------- [public]
--------- [scss]
--------- [src]
--------- package.json
--------- webpack.config.js
---- [server]
--------- index.js
---- [node_modules]
---- package.json
The "client" directory contains the react app. The "server" directory contains the Express app. The Express app's package.json is in the root directory, while react app's package.json is in the "client" directory.
server/index.js
const express = require('express');
const path = require('path');
const PORT = process.env.PORT || 5000;
const app = express();
// Serve static files
app.use(express.static(path.resolve(__dirname, '../client/public')));
app.get('*', function(request, response) {
response.sendFile(path.resolve(__dirname, '../client/public', 'index.html'));
});
app.listen(PORT, function () {
console.error(`Listening on port ${PORT}`);
});
client/package.json
Contains "proxy": "http://localhost:5000"
client/webpack.config.js
Contains the following for devServer, entry, and output (I excluded various loaders as irrelevant for URL processing):
const BUILD_DIR = path.resolve(__dirname, 'build');
const SRC_DIR = path.resolve(__dirname, 'src');
module.exports = (env = {}) => {
return {
entry: {
index: [SRC_DIR + '/index.js']
},
output: {
path: BUILD_DIR,
filename: '[name].bundle.js'
},
devtool: env.prod ? 'source-map' : 'cheap-module-eval-source-map',
devServer: {
contentBase: BUILD_DIR,
compress: true,
hot: true,
open: true,
historyApiFallback: true
}
}
};
client/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import createHistory from 'history/createBrowserHistory';
import { Route } from 'react-router';
import { ConnectedRouter, routerReducer, routerMiddleware, push } from 'react-router-redux';
import rootReducer from './reducers';
// Wrapper
import SiteWrapper from './wrappers/SiteWrapper/'
// Pages
import Error404 from './ErrorPages/Error404/'
const history = createHistory();
const middleware = routerMiddleware(history);
const store = createStore(
combineReducers({
rootReducer,
router: routerReducer
}),
applyMiddleware(middleware)
)
ReactDOM.render((
<Provider store={store}>
<ConnectedRouter history={history}>
<div>
<Route exact path="/404" name="Error 404" component={Error404}/>
<Route path="/" name="Home" component={SiteWrapper}/>
</div>
</ConnectedRouter>
</Provider>
), document.getElementById('root'));
I first run the Express app, which starts listening on port 5000, and then I run the react app. When entering a dynamic URL http://localhost:7500/dynamicurl/test-dynamic-url, the app no longer shows 404, but then it doesn't show anything at all, and this is what I see in the developer console:
Refused to apply style from 'http://localhost:7500/dynamicurl/index.fonts.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
test-dynamic-url:1 Refused to apply style from 'http://localhost:7500/dynamicurl/index.styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
test-dynamic-url:54 GET http://localhost:7500/dynamicurl/index.bundle.js net::ERR_ABORTED
What am I doing wrong here? Did I miss something?
Thanks in advance
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?