There are 3 file created in /config.
default.json
{
"host": "localhost",
"port": "PORT",
"msg": "default"
}
local.json
{
"host": "localhost",
"port": 3030,
"msg": "local"
}
dev.json
{
"host": "localhost",
"port": 3030,
"msg": "dev"
}
Whenever the application runs, it should log something like info: Feathers application started on http://localhost:3030 in dev, which "dev" is the msg variable in config file.
index.js
/* eslint-disable no-console */
const logger = require('./logger');
const app = require('./app');
const port = app.get('port');
const msg = app.get('msg');
const server = app.listen(port);
process.on('unhandledRejection', (reason, p) =>
logger.error('Unhandled Rejection at: Promise ', p, reason)
);
server.on('listening', () =>
logger.info('Feathers application started on http://%s:%d in %s', app.get('host'), port, msg)
);
I tried to set NODE_ENV=dev, but every time I run the application by nodemon --legacy-watch ./src, it shows:
info: Feathers application started on http://localhost:3030 in local
but I am expecting
info: Feathers application started on http://localhost:3030 in dev
I tried to log process.env.NODE_ENV, but it shows dev correctly
app.js
const path = require('path');
const favicon = require('serve-favicon');
const compress = require('compression');
const helmet = require('helmet');
const cors = require('cors');
const logger = require('./logger');
const feathers = require('#feathersjs/feathers');
process.env['NODE_CONFIG_DIR'] = 'config/'. // I tried to add this according to doc but still not working
const configuration = require('#feathersjs/configuration');
const express = require('#feathersjs/express');
const socketio = require('#feathersjs/socketio');
const middleware = require('./middleware');
const services = require('./services');
const appHooks = require('./app.hooks');
const channels = require('./channels');
const authentication = require('./authentication');
const sequelize = require('./sequelize');
const app = express(feathers());
// Load app configuration
app.configure(configuration());
console.log(app.settings.msg); //<--------------------------------- show "local"
console.log(process.env.NODE_ENV); // <---------------------------- show "dev"
// Enable security, CORS, compression, favicon and body parsing
app.use(helmet({
contentSecurityPolicy: false
}));
app.use(cors());
app.use(compress());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
app.use(favicon(path.join(app.get('public'), 'favicon.ico')));
// Host the public folder
app.use('/', express.static(app.get('public')));
// Set up Plugins and providers
app.configure(express.rest());
app.configure(socketio());
app.configure(sequelize);
// Configure other middleware (see `middleware/index.js`)
app.configure(middleware);
app.configure(authentication);
// Set up our services (see `services/index.js`)
app.configure(services);
// Set up event channels (see channels.js)
app.configure(channels);
// Configure a middleware for 404s and the error handler
app.use(express.notFound());
app.use(express.errorHandler({ logger }));
app.hooks(appHooks);
module.exports = app;
Update
After I remove local.json, it works perfectly but it doesn't makes sense?
Related
I am first time experiencing socketio Admin UI. I am facing an issue, I m not abale to view all feature in dashboard. when i visit on https://admin.socket.io/#/ and after successfully login it just shows following menu.
here is my connection snippet.
const app = express();
const http = require('http');
const { instrument } = require("#socket.io/admin-ui");
const server = http.createServer(app);
var io = require("socket.io")(server, {
cors: {
origin: ["https://admin.socket.io"],
credentials: true,
},
});
instrument(io, {
auth: false
});
I want that all feature as shown in that menu.
Sockets
Rooms
Clients
Events
I found the answer. Actually default mode is development but somehow it was not set when i set the mode to development it works fine for me.
const app = express();
const http = require('http');
const { instrument } = require("#socket.io/admin-ui");
const server = http.createServer(app);
var io = require("socket.io")(server, {
cors: {
origin: ["https://admin.socket.io"],
credentials: true,
},
});
instrument(io, {
auth: false,
mode: "development"
});
reference : https://socket.io/docs/v4/admin-ui/#mode
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
We are using CORS to allow all origins
app.use(cors());
server running on port 4000, and client running on 3000
here is my server.js code
const cors = require("cors");
const http = require("http");
const socketIO = require("socket.io");
app.use(cors());
const port = process.env.PORT || process.env.DEFAULT_PORT;
console.log("port: ", port);
app.listen(port, () => {
console.log(`App listening at ${port}...`);
});
const server = http.createServer(app);
const io = new socketIO(server, {
transports: ["websocket"],
});
React js code
constructor(props) {
super(props);
try {
this.socket = io("http://localhost:4000", { transport: ["websocket"] });
this.socket.on("Chat-event", data => {
console.log("socketdata", data);
});
} catch (error) {
console.log("hiterror", error)
}
}
I am continuously getting this error on the client side after allowing origin for all.
Access to XMLHttpRequest at 'http://localhost:4000/socket.io/?EIO=3&transport=polling&t=Mv-SSIc' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute
For socket.io version 3.x.x cors configuration has changed, I managed to fix it by adding options to the socket creation.
Tried on the version 2.x.x also and it worked.
const io = socketio(httpServer, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true
}
});
Here is the resource https://socket.io/docs/v3/handling-cors/
Bonus: In case you encounter Bad Request make sure you have the same version of socket.io for the client and the server.
By following these steps you can get rid of these error.
// 1) on server side
const cors = require('cors');
const socketio = require('socket.io')
const http = require('http');
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: localhost:3000/, //your website origin
methods: ["GET", "POST"],
credentials: true
}
});
// 2) add these middlewares
app.use(cors())
app.options('*', cors());
// 3) on client-side
import io from 'socket.io-client'
let socket = io.connect(localhost:8080, { transports: ['websocket'] }) // your local server
try using the cors credentials config:
app.use(cors({credentials: true}));
Please allow all to socket.io at server side
const socketIO = require('socket.io')(server, { origins: '*:*'});
Or you can set socketIO origins as *
socketIO.set('origins', '*:*');
#user4860402 Gave me solution, thing is that by default npm is installing socket.io client v 2.X.X but on server I'm using latest verion (also provided by npm) 3.0.5
So all problems including 400 error comes because client and server verion doesnot match.
const express = require("express");
const app = express();
const http = require("http").createServer(app);
const socketio = require("socket.io");
const cors = require("cors");
const io = socketio(http, {cors:{origin:"*"}});
Been working fine up until this morning and now, suddenly i am getting a type error stating that Cors is not a function
My code
import * as Cors from "cors";
...
const corsOptions: Cors.CorsOptions = {
allowedHeaders: ["Origin", "X-Requested-With", "Content-Type", "Accept", "X-Access-Token", "Authorization"],
credentials: true,
methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE",
origin: "*",
preflightContinue: true
};
createConnection(ormConfig).then(async connection => {
// run pending migrations
await connection.runMigrations();
// create express server
const app = express();
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true}));
// register cors
app.use(Cors(corsOptions)); //<---error occurs here
// register all controllers
useExpressServer(app, {
routePrefix: "/api",
controllers: [
__dirname + "/controllers/**/*{.js,.ts}"
],
authorizationChecker: async (action: any, roles: string[]) => {
return JwtAuthorizationMiddleware.checkIsAuthorized(action, roles);
},
currentUserChecker: async (actions: any) => {
return JwtAuthorizationMiddleware.extractUserFromJwtToken(actions);
}
});
// start the express server
const port: number = +(process.env.PORT || 44320);
app.listen(port, (err: Error) => {
console.log(`App listening on port ${port}`);
console.log("Press Ctrl+C to quit.");
});
}).catch(error => console.error("TypeORM connection error: ", error));
Current versions of cors and Node
cors: "^2.8.4"
Node: v8.4.0
The only change that recently done was on Friday when I included the following packages
multer: "^1.3.0"
#google-cloud/datastore: "^1.1.0"
#google-cloud/storage: "^1.4.0"
and everything was working till this morning, same version is deployed on gcloud and this works so I am a little bemused as to why I Am suddenly getting this error and what could be the cause.
Any help is greatly appreciated
You have to have something such as
const cors = require('cors');
in the top of your file, and then refer to the module as cors, not Cors.
You can read Express's cors documentation to learn more.
To apply cors to all routes in your project you can write:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
Ok, so I found the problem which turned out to be PEBKAC.
While implementing file uploads and storage in gcloud, I had to enable CORS on gcloud and had saved the settings file in the root of my project, this file was called cors.json.
In the code posted in my question above the import statement was reading my cors.json file and not (as I thought) the cors NPM package.
Lesson learnt from this one should anyone else make the same rookie mistake I just made is be careful what you name your files and where you put them!!!