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.
Related
I have a nodejs application which starts asynchronously because of graphql.
require('custom-env').env();
import { DateTruncAggregateGroupSpecsPlugin } from './subgraphs/db/date_trunc_aggregate_group_specs_plugin';
import PgAggregatesPlugin from "#graphile/pg-aggregates";
import FederationPlugin from "#graphile/federation";
import ConnectionFilterPlugin from "postgraphile-plugin-connection-filter";
const PostGraphileDerivedFieldPlugin = require("postgraphile-plugin-derived-field");
import express from "express";
import { ApolloServer, gql } from "apollo-server-express";
const { makeSchemaAndPlugin } = require("postgraphile-apollo-server");
import pg from 'pg';
import { makeExtendSchemaPlugin } from "graphile-utils";
import { readFileSync } from 'fs';
import { resolve } from 'path';
import resolvers from './resolvers';
export let app = express();
export let server: any;
const { PORT, NODE_ENV, SCHEMA, DATABASE_URL } = process.env;
async function main() {
const { schema, plugin } = await makeSchemaAndPlugin(
new pg.Pool({
connectionString: DATABASE_URL
}),
SCHEMA,
{
subscriptions: false,
appendPlugins: [
FederationPlugin,
ConnectionFilterPlugin,
PostGraphileDerivedFieldPlugin,
PgAggregatesPlugin,
DateTruncAggregateGroupSpecsPlugin,
makeExtendSchemaPlugin((build) => ({
typeDefs: gql(readFileSync(resolve(__dirname, '../graphs/custom.graphql'), { encoding: 'utf-8' })),
resolvers
}))
],
graphileBuildOptions: {
connectionFilterRelations: true
}
}
);
const graphql = new ApolloServer({
debug: false,
schema,
plugins: [plugin],
introspection: true
});
await graphql.start();
graphql.applyMiddleware({
app,
path: '/graphql'
});
server = this.app.listen(PORT, () => console.info(`🚀 Running on PORT ${PORT} 🚀`));
}
main();
The above is my express server that adds graphql to it.
As you can see, the starting of the server is asynchronous.
Now I am using supertest to test APIs end-to-end. Supertest requires app to be passed in.
I need server to start before all tests in my project and tests to be able to use app for supertest reuqest.
How do I do that. With regualar server it is easy as starting of server is not asynchronous, so my app is ready to use by tests. But not in this case. How do I carry out supertest requests.
My api has stopped working, previously it worked fine and as far as i am aware I have changed nothing. When i tested my endpoint i received an internal server error.
Here is a link to my hosted api https://frozen-scrubland-34339.herokuapp.com/api
I have just checked some of my other apis and none are working either, same message. it appears my code isnt the issue but postgres itself?
Any help on what to do would be appreciated
When i tried to npm run prod to re-push it to heroku i received: 'Error: The server does not support SSL connections'
Again this was never an issue previously when it worked.
I imagine i have changed something with heroku itself by accident?
app.js
const express = require("express");
const app = express();
const apiRouter = require("./routers/api-router");
const cors = require("cors");
const {
handle404s,
handlePSQLErrors,
handleCustomError,
} = require("./controllers/errorHandling");
app.use(cors());
app.use(express.json());
app.use("/api", apiRouter);
app.use("*", handle404s);
app.use(handlePSQLErrors);
app.use(handleCustomError);
module.exports = app;
connection.js
const { DB_URL } = process.env;
const ENV = process.env.NODE_ENV || "development";
const baseConfig = {
client: "pg",
migrations: {
directory: "./db/migrations",
},
seeds: {
directory: "./db/seeds",
},
};
const customConfigs = {
development: { connection: { database: "away_days" } },
test: { connection: { database: "away_days_test" } },
production: {
connection: {
connectionString: DB_URL,
ssl: {
rejectUnauthorized: false,
},
},
},
};
module.exports = { ...baseConfig, ...customConfigs[ENV] };
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
I want to host my frontend on Vercel (I'm using Nextjs) and since it doesn't support socket connections in it's API routes I decided to move this part of my app to Heroku. My problem is that when I use the server from my frontend in dev environment it works just fine, but when I deploy it to Heroku I get this error:
Access to XMLHttpRequest at 'https://my-socket-server.herokuapp.com/socket.io/?EIO=3&transport=polling&t=NMPkkyL' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
my server code looks like this:
import express from 'express';
import io, { Namespace } from 'socket.io';
import { PORT, menus, socketServerConfig, adminRoom } from './util/config';
const server = express().listen(PORT, () =>
console.log(`server running on port ${PORT}`)
);
const socketServer = io(server, socketServerConfig);
const attachSocketHandlers = (server: Namespace) => {
server.on('connection', socket => {
const handlers = {
'admin-log-in': () => {
socket.join(adminRoom);
},
'need-waiter': (table: Table) => {
server.to(adminRoom).emit('need-waiter', table);
},
'need-receipt': (table: Table) => {
server.to(adminRoom).emit('need-receipt', table);
},
order: (order: Order) => {
server.to(adminRoom).emit('order', order);
},
disconnect: () => {
socket.leaveAll();
},
};
Object.entries(handlers).map(([event, handler]) => {
socket.on(event, handler);
});
});
};
menus.forEach(menu => {
const namespacedServer = socketServer.of(`/${menu}`);
attachSocketHandlers(namespacedServer);
});
What I understood from the socket.io docs is that if you list no origins in the config it allows all origins to access the socket server.This is my socketServerConfig:
import { ServerOptions } from 'socket.io';
const defaultPort = 4000;
export const PORT = process.env?.PORT ?? defaultPort;
export const menus = ['more'];
export const adminRoom = 'admin';
export const socketServerConfig: ServerOptions = {
serveClient: false, // i don't serve any static files
};
this is how I connect from my frontend:
const url = 'https://my-socket-server.herokuapp.com/';
const io = connect(`${url}${menu}`);
I tried various solutions from SOF but I just can't get it to work, any help would be appreciated. Thanks in advance.
Try doing npm install cors and adding this to your server:
const cors = require('cors');
const whitelist = [
'http://localhost:3000',
YOUR FRONTEND URL
];
const corsOptions = {
origin: function (origin, callback) {
console.log('** Origin of request ' + origin);
if (whitelist.indexOf(origin) !== -1 || !origin) {
console.log('Origin acceptable');
callback(null, true);
} else {
console.log('Origin rejected');
callback(new Error('Not allowed by CORS'));
}
},
};
express().use(cors(corsOptions));
Hope this helped!
I'm trying to create an HTTPS server using node.js and and docker. I have already created the certificates and configured the app. But I don't know how to run the image docker. I am trying this, but it is not working.
Does anyone know how to do this?
sudo docker run --name cont_docker -p 443:3333 --link my-mongo:my-mongo user/docker_app
I am not using docker-compose
---> EDIT <---
The container is not crashing. It is not responding. In the app I get 'couold not connect to server'. I think it is not binding the port
const express = require('express');
const getRootPath = require('../helpers/get-root-path.helper');
var fs = require('fs');
const https = require('https'); // REQUIRE HTTPS
const privateKey = fs.readFileSync('private/key/path', 'utf8');
const certificate = fs.readFileSync('cert/key/path', 'utf8');
let _express = null;
let _config = null;
let _router = null;
let _credentials = null;
class Server {
constructor({ config, router }) {
_router = router;
_config = config;
_credentials = { privateKey: privateKey, certificate: certificate } // ADD CREDENTIALS
_express = express();
}
/*
This methods returns a promisse that will be in charge of initate the server.
*/
start() {
_express.use(express.static(`${this.getRootPath(__dirname)}/public`))
_express.use(_router)
_express.engine('html', require('ejs').renderFile)
_express.set('view engine', 'html')
return new Promise(resolve => {
const server = https.createServer(this._credentials, _express)
server.listen(_config.port, () => {
console.log(`App running on port ${_config.port}`)
resolve()
})
})
}
getRootPath(path) {
return getRootPath(path)
}
}
module.exports = Server
---> APP.JS <---
const container = require('./src/startup/container')
const server = container.resolve("app")
const { db_host, db_database } = container.resolve("config")
const mongoose = require('mongoose')
mongoose.set("useCreateIndex", true)
mongoose
.connect(`mongodb://${db_host}/${db_database}`, { useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false })
.then(response => {
console.log(`Connected to Mongo! Database name: "${response.connections[0].name}" on "${response.connections[0].host}"`)
server.start()
})
.catch(console.log)