简体   繁体   中英

Express environment command line

I need to load an express app into the console so that I could test objects, some data models, work with Sequelize, etc. I need a console for general debugging.

There used to be a way to do this, but I can't remember the trick.

I think it is along the lines of getting into the node console and then requiring app.js somehow.

I am trying to execute User.create() in the console

You can create a local server wrapping app as followed and running node {local server filename} . Then the endpoints are available to hit with postman, a browser, or curl

const app = require('./app');
const port = 8202;

app.listen(port, () => console.log(`Listening on port ${port}!`));

Postman / Browser: http://localhost:8202/users

Curl: curl 'http://localhost:8202/users'


app might look something like this:

const express = require('express');
const app = express();
const User = require('./User);

app.get('/users', (req, resp) => {
    resp.send({
        msg: 'users endpoint',
    });
});

//You will likely want to use postman to handle the post
app.post('/users', (req, resp) => {
    User.Create(req.body);
    resp.send({
        msg: 'user created',
    });
});
module.exports = app;

I don't think you can use it doing express that way. But if your model is set up a certain way you could use node to load your model and call it through that...

User.js

module.exports = {
  Create: (data) => { 
    console.log(data);
    //do other stuff
    return true; 
  }
}

you can then access it in node...

-> node
-> const User = require('./user')
undefined
-> User.Create({test: 'test'})
{test: 'test'}
true

For sequelize specifically, you will want to use the async flag to troubleshoot. The method below will load all the models

node --experimental-repl-await

> models = require('./models'); //requires all models
> User = models.User; //however you load the model in your actual app this may vary
> await User.create({name:"Hoosier"}); //use await to avoid promise errors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM