Home Gets Error when adding MySQL information in server.js when creating RESTful API with Express
Reply: 0

Gets Error when adding MySQL information in server.js when creating RESTful API with Express

user2359 Published in June 25, 2018, 12:19 am

I was following instructions to build a RESTful API with Express and MySQL(*1) But when I change

app.listen(port); //excutable, GET returns welcome message



in the part 2 of(*1), which is adding MySQL information into server.js, I gets the following on Node.JS command prompt:

TypeError: Cannot read property 'bear' of undefined

Because this is the first attempt in building RESTful API, I'm not sure what to do to fix it. Help please! Any idea is appreciated. full code of server.js: // server.js

var util = require('util');

var express    = require('express');     
var app        = express();                 
var bodyParser = require('body-parser');
var Waterline    = require('waterline');

var Bear         = require('./app/models/bear');
var WConfig = require('./app/config/waterline');

var orm = new Waterline();

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

var port = process.env.PORT || 8080;        

var router = express.Router();             

router.get('/', function(req, res) {
    res.json({ message: 'hello! welcome to our api!' });   

app.use('/api', router);
// express deprecated res.json(obj,status): use res.status(status).json(obj) instead 
    .post(function(req,res) {
        app.models.bear.create(req.body,function(err,model) {
            if(err) return res.status(500).json({ err,err });
            res.json(model);   //res.json(model) , guess: res.status(200).json(model);

//gets error if I change it to following 
    if(err) throw err;
    app.models = models.collections;
    app.connections = models.connections;


    console.log('Magic happens on port ' + port);

reference: 1.Create Restful API with Express and waterline (in Chinese) https://segmentfault.com/a/1190000004996659#articleHeader2

2.Build a RESTful API Using Node and Express 4 https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.307064 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO