Error no default engine was specified and no extension was provided express

I am working through setting up a http server using node.js and engine. However, I keep running into issues that I have little information on how to resolve I would appreciate some help solving this

I am working through setting up a http server using node.js and engine. However, I keep running into issues that I have little information on how to resolve I would appreciate some help solving this please.

Error: No default engine was specified and no extension was provided. 
at new View (...node_modulesexpresslibview.js:41:42) 
at Function.app.render (...node_modulesexpresslibapplication.js:484:12) 
at ServerResponse.res.render (...node_modulesexpresslibresponse.js:783:7) 
at Layer.handle (...app.js:123:7) 
at trim_prefix (...node_modulesexpresslibrouterindex.js:225:17) 
at c (...node_modulesexpresslibrouterindex.js:198:9) 
at Function.proto.process_params (...node_modulesexpresslibrouterindex.js:253:12) 
at next (...node_modulesexpresslibrouterindex.js:189:19) 
at next (...node_modulesexpresslibrouterindex.js:202:7) 
at next (...node_modulesexpresslibrouterindex.js:166:38)

Below is what I have set up to start up this engine.

var http = require('http');  
var module = require("module")
var logger = require('morgan');
var express = require('express');
var app =  module.exports = express();
var silent = 'test' == process.env.NODE_ENV;
var httpServer = http.createServer(app);  // app middleware

app.enable('strict routing');
// app.all('*', function(req, res, next)/*** CORS support.*/
// {
//   if (!req.get('Origin')) return next();// use "*" here to accept any origin
//   res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
//   res.set('Access-Control-Allow-Methods', 'GET, POST');
//   res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
//   res.set('Access-Control-Allow-Max-Age', 3600);
//   if ('OPTIONS' == req.method) return res.send(200);
//   next();
// });
app.set('views', __dirname + '/views'); // general config
app.set('view engine', 'html');
app.get('/404', function(req, res, next){
next();// trigger a 404 since no other middleware will match /404 after this one, and we're not responding here
});
app.get('/403', function(req, res, next){// trigger a 403 error
  var err = new Error('not allowed!');
  err.status = 403;
  next(err);
});
app.get('/500', function(req, res, next){// trigger a generic (500) error
  next(new Error('keyboard cat!'));
});
app.use(express.static(__dirname + '/public')); 
//error handlers
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);  
// middleware with an arity of 4 are considered error handling middleware. When you next(err)
// it will be passed through the defined middleware in order, but ONLY those with an arity of 4, ignoring regular middleware.
function clientErrorHandler(err, req, res, next) {
  if (req.xhr) {// whatever you want here, feel free to populate properties on `err` to treat it differently in here.
  res.send(err.status || 500, { error: err.message });
  } 
  else 
  { next(err);}
};
// create an error with .status. we can then use the property in our custom error handler (Connect repects this prop as well)
function error  (status, msg) {
  var err = new Error(msg);
  err.status = status;
  return err;
};
function logErrors  (err, req, res, next) {
  console.error(err.stack);
  next(err);
};
function errorHandler (err, req, res, next) {
  res.status(500);
  res.render('error', { error: err });
};

// Error handlers
// Since this is the last non-error-handling middleware use()d, we assume 404, as nothing else responded.
// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"
app.use(function(req, res, next){
  res.status(404); 
  if (req.accepts('html')) {// respond with html page
    res.render('404', { url: req.url });
    return;
  } 
  if (req.accepts('json')) {// respond with json
    res.send({ error: 'Not found' });
    return;
  } 
  res.type('txt').send('Not found');// default to plain-text. send()
});

// error-handling middleware, take the same form as regular middleware, however they require an
// arity of 4, aka the signature (err, req, res, next).when connect has an error, it will invoke ONLY error-handling middleware.

// If we were to next() here any remaining non-error-handling middleware would then be executed, or if we next(err) to
// continue passing the error, only error-handling middleware would remain being executed, however here
// we simply respond with an error page.
app.use(function(err, req, res, next){
  // we may use properties of the error object here and next(err) appropriately, or if we possibly recovered from the error, simply next().
  res.status(err.status || 500);
  res.render('500', { error: err });
});

if (!module.parent) {// assigning to exports will not modify module, must use module.exports
  app.listen(3000);
  silent || console.log('Express started on port 3000');
};

Could you help me please what’s wrong in my Express code? I cannot understand.

Here is my server.js file:

const path = require('path');
const express = require('express');
const nodemailer = require('nodemailer');
const webpack = require('webpack');
const webpackMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const config = require('./webpack.config.js');

const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 8016 : process.env.PORT;
const app = express();

if (isDeveloping) {
  const compiler = webpack(config);
  const middleware = webpackMiddleware(compiler, {
    publicPath: config.output.publicPath,
    contentBase: 'src',
    stats: {
      colors: true,
      hash: false,
      timings: true,
      chunks: false,
      chunkModules: false,
      modules: false
    }
  });

  app.use(middleware);
  app.use(webpackHotMiddleware(compiler));
  app.get('/', function response(req, res) {
    res.write(middleware.fileSystem.readFileSync(path.join(__dirname, '../dist/index.html')));
    res.end();
  });

  app.post('/contact', function (req, res) {
    var mailOpts, smtpTrans;
    smtpTrans = nodemailer.createTransport('SMTP', {
      service: 'Gmail',
      auth: {
        user: "some-my-email@gmail.com",
        pass: "password-of-this-email"
      }
    });
    mailOpts = {
      from: 'noreply@my-email.io>',
      to: 'my-email@gmail.com',
      subject: 'Website contact form',
      text: req.body.message
    };
    smtpTrans.sendMail(mailOpts, function (error, response) {
      if (error) {
        res.render('contact', {
          err: true, page: 'contact'
        })
      }
      else {
        res.render('contact', {
          err: false, page: 'contact'
        })
      }
    });
  });
} else {
  app.use(express.static(__dirname + '../dist'));
  app.get('/', function response(req, res) {
    res.sendFile(path.join(__dirname, '../dist/index.html'));
  });
}

app.listen(port, '0.0.0.0', function onStart(err) {
  if (err) {
    console.log(err);
  }
  console.info('==> 🌎  Listening on port %s. Open up http://0.0.0.0:%s/ in your browser.', port, port);
});

All works good, but when I added Nodemailer to my project it takes me an error message when I’m sending form:

There are two errors. If text of mailOpts is «req.body.message» there is this error:

TypeError: Cannot read property 'message' of undefined
   at /home/azat/git/azat-io/scripts/server.js:50:21
   at Layer.handle [as handle_request] (/home/azat/git/azat-io/node_modules/express/lib/router/layer.js:95:5)
   at next (/home/azat/git/azat-io/node_modules/express/lib/router/route.js:131:13)
   at Route.dispatch (/home/azat/git/azat-io/node_modules/express/lib/router/route.js:112:3)
   at Layer.handle [as handle_request] (/home/azat/git/azat-io/node_modules/express/lib/router/layer.js:95:5)
   at /home/azat/git/azat-io/node_modules/express/lib/router/index.js:277:22
   at Function.process_params (/home/azat/git/azat-io/node_modules/express/lib/router/index.js:330:12)
   at next (/home/azat/git/azat-io/node_modules/express/lib/router/index.js:271:10)
   at middleware (/home/azat/git/azat-io/node_modules/webpack-hot-middleware/middleware.js:39:48)
   at Layer.handle [as handle_request] (/home/azat/git/azat-io/node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (/home/azat/git/azat-io/node_modules/express/lib/router/index.js:312:13)
   at /home/azat/git/azat-io/node_modules/express/lib/router/index.js:280:7
   at Function.process_params (/home/azat/git/azat-io/node_modules/express/lib/router/index.js:330:12)
   at next (/home/azat/git/azat-io/node_modules/express/lib/router/index.js:271:10)
   at processRequest (/home/azat/git/azat-io/node_modules/webpack-dev-middleware/middleware.js:176:12)
   at ready (/home/azat/git/azat-io/node_modules/webpack-dev-middleware/middleware.js:96:20)

If text of mailOpts is just string «Hello!» there is this error:

Error: No default engine was specified and no extension was provided.
   at new View (/home/azat/git/azat-io/node_modules/express/lib/view.js:62:11)
   at EventEmitter.render (/home/azat/git/azat-io/node_modules/express/lib/application.js:569:12)
   at ServerResponse.render (/home/azat/git/azat-io/node_modules/express/lib/response.js:961:7)
   at /home/azat/git/azat-io/scripts/server.js:54:13
   at Nodemailer.sendMail (/home/azat/git/azat-io/node_modules/nodemailer/lib/nodemailer.js:265:16)
   at /home/azat/git/azat-io/scripts/server.js:52:15
   at Layer.handle [as handle_request] (/home/azat/git/azat-io/node_modules/express/lib/router/layer.js:95:5)
   at next (/home/azat/git/azat-io/node_modules/express/lib/router/route.js:131:13)
   at Route.dispatch (/home/azat/git/azat-io/node_modules/express/lib/router/route.js:112:3)
   at Layer.handle [as handle_request] (/home/azat/git/azat-io/node_modules/express/lib/router/layer.js:95:5)
   at /home/azat/git/azat-io/node_modules/express/lib/router/index.js:277:22
   at Function.process_params (/home/azat/git/azat-io/node_modules/express/lib/router/index.js:330:12)
   at next (/home/azat/git/azat-io/node_modules/express/lib/router/index.js:271:10)
   at middleware (/home/azat/git/azat-io/node_modules/webpack-hot-middleware/middleware.js:39:48)
   at Layer.handle [as handle_request] (/home/azat/git/azat-io/node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (/home/azat/git/azat-io/node_modules/express/lib/router/index.js:312:13)

Help me please, what is wrong here?

The programming error “error: no default engine was specified and no extension was provided” is already self-explanatory. It occurs when the default engine is missing or is not installed on the computer.Fix the no default engine was specified and no extension was provided

This article will supply relevant knowledge of this error and various methods to solve it with the help of suitable examples. Let’s begin!

The error: no default engine was specified and no extension was provided. error occurs due to the absence of a default engine that did not contain any extension at the time of execution of the program and sometimes due to the absence of HTML complying syntax.

However, besides this main issue, there are other problems that create this error such as:

  • Using res.render in the wrong way.
  • The view engine is missing.
  • Not using HTML-friendly syntax.
  • Compatibility issues.
  • The library is used first.
  • Spelling error in functions.

– Using Res.Render in the Wrong Way

The default engine error will occur when the res.render function is misused. The programmer should not use the res.render function in the program without a view engine.Causes of no default engine was specified and no extension was provided

If, for example, the programmer wants to serve JSON using res.render with “res.render(‘error’, { error: err });” function, the error message will be displayed. There are two reasons why it is wrong. First, the view engine is not used to support this command; second, there is a syntax error.

– The View Engine Is Missing

This error message occurs when the view engine is missing or has the wrong placement in the program. Moreover, sometimes, the view engine does exist, but it is used with non-friendly HTML software, which is incompatible and ends up showing an error. The following example will not be suitable for those who don’t have software that supports HTML.

For example:

app.set(‘view engine’, ‘HTML’);

– Not Using HTML-friendly Syntax

As mentioned above, if the programmer uses software that does not support HTML, a view engine software error will occur. For example, if the programmer only uses the “app.set(‘view engine’, ‘HTML’);” command in a non-friendly HTML software, the program will show an error message.

Without “ejs” the error will not be resolved. This is because ejs is a function that can be used in software that does not support HTML, and if it is not used, the error will occur. Due to these reasons, an error: cannot find module ‘HTML’ can occur. Moreover, in a program that supports ejs but the user has used HTML, another type of error can occur that says: error: cannot find module ‘ejs’.

– Compatibility Issues

Sometimes, compatibility issues can also create extension errors in the program. The word compatibility means the function or commands the programmer uses are not updated, and the software does not support that command or function. Therefore, the user has to use the updated commands.More causes of no default engine was specified and no extension was provided

For example, using “response.sendfile(‘index.html’);” in programs will show an extension error message. This is because the response.sendfile() function is deprecated and not updated.

– The Library Is Used First

Another reason a view engine error occurs is that the library is created before the view engine. A program needs the view engine first to run the program smoothly. Therefore, if the programmer has created a library at the beginning of the program and then mentioned the view engine, the program will not run.

Let’s understand this by using an example. Check how the programmer has made a minor mistake, and the program showed an “error: no default engine was specified, and no extension was provided.” error message.

Example:

const express = require(‘express’);

const expressLayouts = require(‘express-ejs-layouts’);

const app = express();

// Ejs

app.use(expressLayouts);

app.set(‘view engine’, ‘ejs’)

// routes

app.use(‘/’, require(‘./routes/index’));

app.use(‘/users’, require(‘./routes/users’));

const PORT = process.env.PORT || 6000;

app.listen(PORT, console.log(‘server started on port ${PORT}’));

const express = require(‘express’);

const router = express.Router();

router.get(‘/’, (req, res) => res.render(‘hello’));

module.exports = router;

// There is a hello.ejs file in the views folder.

– Spelling Errors in Functions

Sometimes programmers end up with syntax errors due to spelling mistakes in the functions. In the example below, the programmer has made a spelling mistake, due to which a view engine error occurred. Let’s use the same example mentioned above for a better understanding:

Program:

const express = require(‘express’);

const expressLayouts = require(‘express-ejs-layouts’);

const app = express();

// Ejs

app.use(expressLayouts);

app.set(‘veiw engine’, ‘ejs’)

// routes

app.use(‘/’, require(‘./routes/index’));

app.use(‘/users’, require(‘./routes/users’));

const PORT = process.env.PORT || 6000;

app.listen(PORT, console.log(‘server started on port ${PORT}’));

const express = require(‘express’);

const router = express.Router();

router.get(‘/’, (req, res) => res.render(‘hello’));

module.exports = router;

//There is a hello.ejs file in the views folder.

Explanation:

As you can see, the spelling of view is written as “veiw”. Thus, it is causing an error in the program. This is also known as a syntax error.

How To Resolve the “Error: No Default Engine Was Specified and No Extension Was Provided.” Error Message?

In order to fix the error: no default engine was specified, and no extension was provided., the programmer has to resolve syntax errors that are affecting extensions and ensure the presence of the view engine because, without it, the program will not run.

However, there are various other reasons, and they are explained below:

– Use Res.Render Properly

As mentioned above, do not use res.render without a view engine; otherwise, a view engine error message will occur. In order to resolve this error, see the below example. We have also provided an explanation of this program.

Error in Program:

var http = require(‘http’);

var module = require(“express”)

var logger = require(‘morgan’);

var express = require(‘module’);

var app = module.exports = express();

var silent = ‘test’ == process.env.NODE_ENV;

var httpServer = http.createServer(app); // app middleware

app.enable(‘strict the routing’);

// app.all(‘*’, function(res, req, next)/*** CORS support.*/

// {

// if (!req.get(‘Origin’)) return next();

// use (*) here to accept any origin

// res.set(‘Access-Control-Allow-Origin’, ‘http://localhost:4000’);

// res.set(‘Access-Control-Allow-Methods’, ‘GET, POST’);

// res.set(‘Access-Control-Allow-Headers’, ‘X-Requested-With, Content-Type’);

// res.set(‘Access-Control-Allow-Max-Age’, 4500);

// if (‘OPTIONS’ == req.method) return res.send(300);

// next();

// });

app.set(‘view’, __dirname + ‘/view’); // general config

app.set(‘viewengine’, ‘HTML’);

app.get(‘/404’, function(res, req, next) {

next();

});

app.get (‘/403’, function(res, req, next){// trigger a 403 error

var err = new Error(‘it is not allowed!’);

err.status = 403;

next(err);

});

app.get(‘/600’, function(req, res, next){// trigger a generic (600) error

next(new Error(‘keyboard-cat!’));

});

app.use(express.static(_dirname + ‘/public’));

//error-handlers

app.use (log.Errors);

app.use (client.Error.Handler);

app.use (error.Handler);

// middleware with an arity of “4” are error-handling middleware. When the next(err)

// it will pass through the defined middleware in sequence, but only those with an arity of “4”.

function clientErrorHandler(err, req, res, next) {

if (req.xhr) {// whatever you want here, feel free to populate properties on `err` to treat it differently here.

res.send(err.status || 600, { error: err.message });

}

else

{ next(err);}

};

// create an error with .status. The user can then use the property in their custom error handler

function error (status, msg) {

var err = new Error(msg);

err.status = status;

return err;

};

function logErrors (err, req, res, next) {

console.error(err.stack);

next(err);

};

function errorHandler (err, req, res, next) {

res.status(600);

res.render(‘error’, { error: err });

};

Explanation:

As you can see, the programmer has used res.render incorrectly. If the programmer just wants to serve JSON, then they should replace the “res.render(‘error’, { error: err });” lines in their code with “res.json({ error: err });”.

It is a must to express render in the program. Moreover, when this program is executed, there will be a message in the returned object that says:

res.status(err.status || 600);

res.json({

message: err.message,

error: err

});

– Add the Correct View Engine

The programmer has to be careful with the functions they write with the view engine. A view engine error message will occur if it is wrong or not supported by the program’s software.Solutions for no default engine was specified and no extension was provided

Let’s use the above example that is used in “Use res.render properly” and change the “app.set(‘view engine’, ‘HTML’);” to “app.set(‘view engine’, ‘jade’);”. By doing this, the program error will be removed.

Moreover, the programmer has to install the default view engine and has to use the express view engine command in their programs. This is because if the programmer hasn’t used it in the program while coding, an “express no view engine” error message will pop up.

– Do Not Use the Library Before View Engine

The programmer should not use a library before a view engine in any program. This is because the program will not run smoothly then. Therefore, the programmer should set the view engine and use the express-ejs-layouts library later.

For Example:

app.set(‘view engine’, ‘ejs’);

app.use(expressLayouts);

Correct Program:

const express = require(‘express’);

const expressLayouts = require(‘express-ejs-layouts’);

const app = express();

// Ejs

app.set(‘view engine’, ‘ejs’)

app.use(expressLayouts);

// routes

app.use(‘/’, require(‘./routes/index’));

app.use(‘/users’, require(‘./routes/users’));

const PORT = process.env.PORT || 6000;

app.listen(PORT, console.log(`server started on port ${PORT}`));

const express = require(‘express’);

const router = express.Router();

router.get(‘/’, (req, res) => res.render(‘hello’));

module.exports = router;

Conclusion

After reading this guide thoroughly, the reader will be able to identify the reason behind this error and can easily solve this issue due to the solutions given in this article. Here’s a quick recap for the readers:

Before starting to code, ensure the installation of the default engine in the computer. By doing so, the user can use it in their program later and avoid errors.

This error also occurs when the programmer does not recognize the extension. For example, using “HTML” instead of “Jade” or “ejs”.

Put the *.html in the views directory. Another way is to serve a public directory as a static dir and put the index.html in the public dir.

The reader can use this guide to resolve their programming error dilemma easily. Thank you for reading!

Reference

  • https://stackoverflow.com/questions/23595282/error-no-default-engine-was-specified-and-no-extension-was-provided
  • https://forum.freecodecamp.org/t/i-need-help-with-this-guys-error-no-default-engine-was-specified-and-no-extension-was-provided/446509
  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

Issue

I cannot get my api to work with my express server, I always get an error:

Error: No default engine was specified and no extension was provided.

I am pretty sure it is coming from express router but I cannot find where the error comes from…

Did I use express router correctly? Because I have never used it before.

server.js:

const createError = require('http-errors');
const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const api = require('./routes/api');
const app = express();
const MongoClient = require('mongodb').MongoClient;

const MONGODB_URI = process.env.MONGODB_URI;
const PORT = process.env.PORT || 5000;

app.use('/', api);

app.use(logger('dev'));

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

// Database object
var db;

// Initialize connection once with db
MongoClient.connect(MONGODB_URI, function(err, database) {
    if(err) throw err;

    db = database;

    // Start the application after the database connection is ready
    app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
});

module.exports = db;
module.exports = app;

routes/api.js:

// const app = require("../server");
var db = require("../server");
const { videos } = require("../helpers/videos");
const { videoLinksValidator } = require("../helpers/video-links-validator");
const { getTitleType } = require("../helpers/title-type-extractor");
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
    console.log("RESPONSE", res) 
});

// Create a GET route
router.get("/express_backend", (req, res) => {
    res.send({ express: "YOUR EXPRESS BACKEND IS CONNECTED TO REACT" });
});

router.post("/video_url", async (req, res)=> {
    const videoURL = req.body.videoURL.videoURL;

    let titleType = await getTitleType(videoURL);

    let videosAndTitle = await videos(videoURL, titleType);

    let videoAndTitleReady = await videoLinksValidator(videosAndTitle);
    console.log(videoAndTitleReady)
    return res.send(videoAndTitleReady);
});

module.exports = router;

Solution

This error is because you are using res.render. res.render will try to render the page for that you have to set view engine like jade etc. But here you do not need that so change res.render to res.send like this

Try this

app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.send('error');//this or res.status(err.status || 500).send('error')
});

For your second question you have to bring bodyParser at the top like this in server.js

app.use(bodyParser.json()); //here
app.use('/', api);

app.use(logger('dev'));

//app.use(bodyParser.json()); your old code

Answered By – Rajan Lagah

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

При отправки формы регистрации, данные заносятся в бд, но пишет ошибку в консоль и не переадресовывает на нужный компонент (Main).

Ошибка:

Error: No default engine was specified and no extension was provided.
    at new View (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/view.js:61:11)
    at Function.render (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/application.js:570:12)
    at ServerResponse.render (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/response.js:1012:7)
    at exp.signup (/Users/daniilboyko/Desktop/quiz/quiz/server/app/controllers/authcontroller.js:4:9)
    at Layer.handle [as handle_request] (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/layer.js:95:5)
    at /Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:275:10)
    at SessionStrategy.strategy.pass (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/passport/lib/middleware/authenticate.js:343:9)
    at SessionStrategy.authenticate (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/passport/lib/strategies/session.js:75:10)
    at attempt (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/passport/lib/middleware/authenticate.js:366:16)
    at authenticate (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/passport/lib/middleware/authenticate.js:367:7)
    at Layer.handle [as handle_request] (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:317:13)
    at /Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:275:10)
    at initialize (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/passport/lib/middleware/initialize.js:53:5)
    at Layer.handle [as handle_request] (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/layer.js:95:5)

app/routes/auth.js

const authController = require('../controllers/authcontroller');
 
 
module.exports = function(app, passport) {
 
    app.get('/signup', authController.signup);
 
    app.get('/signin', authController.signin);

    app.get('/main', authController.main);

    app.post('/signup', passport.authenticate('local-signup', {
            successRedirect: '/main',
 
            failureRedirect: '/signup'
        }
 
    ));
}

app/controllers/authcontroller.js

let exp = module.exports = {};
 
exp.signup = function(req, res) {
    res.render('signup');
}

exp.signin = function(req, res) {
    res.render('signin');
}

exp.main = function(req, res) {
 
    res.render('main');
 
}

app/config/passport/passport.js

const bCrypt = require('bcrypt-nodejs')

module.exports = function(passport, user) {
	const User = user;
	const LocalStrategy = require('passport-local').Strategy;

	passport.use('local-signup', new LocalStrategy(
		{
			usernameField: 'email',
			passwordField: 'password',
			passReqToCallback: true 
		},
	
		function(req,email, password, done) {
			let generateHash = function(password) {
				return bCrypt.hashSync(password, bCrypt.genSaltSync(8), null); 
				};
		User.findOne({
			where: {
				email: email
			}
		}).then(function(user) {
			if (user)
			{
				return done(null, false, {
					message: 'That username is already taken'
			});
			} else {
					let userPassword = generateHash(password);
					const data =
							{
									email: email,
									password: userPassword,
									username: req.body.username
							};
					User.create(data).then(function(newUser, created) {
							if (!newUser) {
								return done(null, false);
							}
							if (newUser) {
								return done(null, newUser);
							}
						});
				}
		});
		}
	));

	passport.serializeUser(function(user, done) {
    done(null, user.id);
	});

	// deserialize user 
passport.deserializeUser(function(id, done) {
	User.findByPk(id).then(function(user) {
			if (user) {
					done(null, user.get());
			} else {
					done(user.errors, null);
			}
	});
});
}

server.js

const express = require("express");
const path = require("path");

const app = express();
const passport   = require('passport')
const session    = require('express-session')
const bodyParser = require("body-parser");

const env = require('dotenv');

// For Body Parser
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,"../public")));

// For Passport
app.use(session({ secret: 'keyboard cat',resave: true, saveUninitialized:true})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

//Models
const models = require("./app/models");

//Routes
const authRoute = require('./app/routes/auth.js')(app,passport);
//load passport strategies
require('./config/passport/passport')(passport, models.user);
 
//Sync Database
models.sequelize.sync().then(function() {
    console.log('Nice! Database looks fine')
}).catch(function(err) {
    console.log(err, "Something went wrong with the Database Update!") 
});

app.listen(4000,function(){
	console.log("Started listening on port", 4000);
})

Компонент регистрации:

import React, { Component } from 'react'
import axios from 'axios'
import {
  Form,
  Input,
  Button,
} from 'antd';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
};


const onFinish = values => {
	axios.post('/signup', {
		username: values.username,
		email: values.email,
		password: values.password
	})
	.then(function (response) {
		console.log(response);
	})
	.catch(function (error) {
		console.log(error);
	});
	console.log('Received values of form: ', values);
};

export default class SignUp extends Component {
	styles = {
		wrap: {
			height: "100%",
			display: "flex",
			justifyContent: "center",
			alignItems: "center"
		},
	
		formStyle : {
			width: "500px",
		},
	}
	render() {
		return (
			<div style={this.styles.wrap}>
				<Form
					{...formItemLayout}
					name="register"
					onFinish={onFinish}
					scrollToFirstError
					style={this.styles.formStyle}
					> 
					<Form.Item
						name="username"
						label="Имя пользователя"
						rules={[{ required: true, message: 'Введите имя пользователя!', whitespace: true }]}>
						<Input />
					</Form.Item>

					<Form.Item
						name="email"
						label="E-mail"
						rules={[
							{
								type: 'email',
								message: 'Неправильно введен E-mail!',
							},
							{
								required: true,
								message: 'Введите E-mail!',
							},
						]}
					>
					<Input />
					</Form.Item>

					<Form.Item
        		name="password"
						label="Пароль"
						rules={[
							{
								required: true,
								message: 'Введите пароль!',
							},
						]}
						hasFeedback>
						<Input.Password />
					</Form.Item>

					<Form.Item
							name="confirm"
							label="Подтвердить пароль"
							dependencies={['password']}
							hasFeedback
							rules={[
								{
									required: true,
									message: 'Подтвердите пароль!',
								},
								({ getFieldValue }) => ({
									validator(rule, value) {
										if (!value || getFieldValue('password') === value) {
											return Promise.resolve();
										}
										return Promise.reject('Пароли не совпадают!');
									},
								}),
							]}>
							<Input.Password />
					</Form.Item>

					<Form.Item {...tailFormItemLayout}>
						<Button type="primary" htmlType="submit">
							Регистрация
						</Button>
      		</Form.Item>

				</Form>
			</div>
		)
	}
}

The res.render stuff will throw an error if you’re not using a view engine.

If you just want to serve json replace the res.render('error', { error: err }); lines in your code with:

res.json({ error: err })

PS: People usually also have message in the returned object:

res.status(err.status || 500);
res.json({
  message: err.message,
  error: err
});

You are missing the view engine, for example use jade:

change your

app.set('view engine', 'html');

with

app.set('view engine', 'jade');

If you want use a html friendly syntax use instead ejs

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

EDIT

As you can read from view.js Express View Module

module.exports = View;

/**
 * Initialize a new `View` with the given `name`.
 *
 * Options:
 *
 *   - `defaultEngine` the default template engine name
 *   - `engines` template engine require() cache
 *   - `root` root path for view lookup
 *
 * @param {String} name
 * @param {Object} options
 * @api private
 */

function View(name, options) {
  options = options || {};
  this.name = name;
  this.root = options.root;
  var engines = options.engines;
  this.defaultEngine = options.defaultEngine;
  var ext = this.ext = extname(name);
  if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');
  if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
  this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
  this.path = this.lookup(name);
}

You must have installed a default engine

Express search default layout view by program.template as you can read below:

mkdir(path + '/views', function(){
      switch (program.template) {
        case 'ejs':
          write(path + '/views/index.ejs', ejsIndex);
          break;
        case 'jade':
          write(path + '/views/layout.jade', jadeLayout);
          write(path + '/views/index.jade', jadeIndex);
          break;
        case 'jshtml':
          write(path + '/views/layout.jshtml', jshtmlLayout);
          write(path + '/views/index.jshtml', jshtmlIndex);
          break;
        case 'hjs':
          write(path + '/views/index.hjs', hoganIndex);
          break;

      }
    });

and as you can read below:

program.template = 'jade';
if (program.ejs) program.template = 'ejs';
if (program.jshtml) program.template = 'jshtml';
if (program.hogan) program.template = 'hjs';

the default view engine is jade

node.js – Error: No default engine was specified and no extension was provided

Comment out the res.render lines in your code and add in next(err); instead. If you’re not using a view engine, the res.render stuff will throw an error.

Sorry, you’ll have to comment out this line as well:

app.set('view engine', 'html');

My solution would result in not using a view engine though. You don’t need a view engine, but if that’s the goal, try this:

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//swap jade for ejs etc

You’ll need the res.render lines when using a view engine as well. Something like this:

// error handlers
// development error handler
// will print stacktrace
if (app.get(‘env’) === ‘development’) {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render(‘error’, {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
next(err);
res.render(‘error’, {
message: err.message,
error: {}
});
});

Related posts on node js :

  • node.js – Make pm2 log to console
  • node.js – How can I validate number of digits from joi using nodejs?
  • node.js – LRU Cache in Node js
  • node.js – How to specify node version in heroku
  • node.js – How can I execute a bin with yarn?
  • node.js – Angular 2 accessing mongoDB data
  • node.js – Retries in AWS Lambda
  • node.js – npm install from tgz created with npm pack

Экспресс — ошибка: не указан механизм по умолчанию и не предоставлено расширение.

Я не могу заставить свой api работать с моим экспресс-сервером, я всегда получаю сообщение об ошибке:

Error: No default engine was specified and no extension was provided.

Я почти уверен, что он исходит от экспресс-роутера, но я не могу найти, откуда взялась ошибка …

Правильно ли я использовал экспресс-роутер? Потому что раньше я этим не пользовался.

Server.js:

const createError = require('http-errors');
const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const api = require('./routes/api');
const app = express();
const MongoClient = require('mongodb').MongoClient;

const MONGODB_URI = process.env.MONGODB_URI;
const PORT = process.env.PORT || 5000;

app.use('/', api);

app.use(logger('dev'));

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

// Database object
var db;

// Initialize connection once with db
MongoClient.connect(MONGODB_URI, function(err, database) {
    if (err) throw err;

    db = database;

    // Start the application after the database connection is ready
    app.listen(PORT, () => console.info(`Server listening on port ${PORT}`));
});

module.exports = db;
module.exports = app;

Маршруты / api.js:

// const app = require("../server");
var db = require("../server");
const { videos } = require("../helpers/videos");
const { videoLinksValidator } = require("../helpers/video-links-validator");
const { getTitleType } = require("../helpers/title-type-extractor");
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
    console.info("RESPONSE", res) 
});

// Create a GET route
router.get("/express_backend", (req, res) => {
    res.send({ express: "YOUR EXPRESS BACKEND IS CONNECTED TO REACT" });
});

router.post("/video_url", async (req, res)=> {
    const videoURL = req.body.videoURL.videoURL;

    let titleType = await getTitleType(videoURL);

    let videosAndTitle = await videos(videoURL, titleType);

    let videoAndTitleReady = await videoLinksValidator(videosAndTitle);
    console.info(videoAndTitleReady)
    return res.send(videoAndTitleReady);
});

module.exports = router;

Jerlam, 20 сентября 2018 г., 19:20

7

27 538

3


Ответы:

Решено

Эта ошибка возникает из-за того, что вы используете res.render. res.render попытается отобразить страницу, для которой вы должны установить механизм просмотра, например jade и т. д. Но здесь вам это не нужно, поэтому измените res.render на res.send, как это
Попробовать

app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.send('error');//this or res.status(err.status || 500).send('error')
});

Для вашего второго вопроса вы должны вывести bodyParser вверху, как это в server.js

app.use(bodyParser.json()); //here
app.use('/', api);

app.use(logger('dev'));

//app.use(bodyParser.json()); your old code

Rajan, 20 сентября 2018 г., 19:26

В вашем коде вы выполняете рендеринг, а если ваш механизм просмотра не работает, вы получите ошибку.

   res.status(err.status || 500);
    res.render('error');

Поэтому, если вы используете свое приложение в качестве шлюза API, вы должны отправить эти ответы. В соответствии с отправкой в ​​настоящее время не рекомендуется использовать

  res.status(err.status || 500).send('error');

king, 26 сентября 2019 г., 12:51

У меня была такая же ошибка. Я забыл добавить приведенный ниже синтаксис в файл server.js

//set default engine, and provide [handlebars as] extension
app.set('view engine', 'handlebars');

agelgel, 29 октября 2019 г., 19:37

Интересные вопросы для изучения

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error no database selected hibernate
  • Error no connection принтер
  • Error no connection to the database itop
  • Error launching winpty agent
  • Error no configuration file found no default or ui configuration directive found

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии