S
S
Speakermen2021-07-24 23:59:15
Express.js
Speakermen, 2021-07-24 23:59:15

Why is this TypeError: Cannot create property 'next' on string '/' req.next = next?

index.js

const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');

const posts = require('./routes/posts');

dotenv.config({ path: './config/config.env' });

const app = express();

app.use('/api/posts', posts);

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

mongoose.connect('...', {useNewUrlParser: true, useUnifiedTopology: true});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})


routes/posts.js

const express = require('express');

//const { index, create, store, show, edit, update, destroy } = require('../controllers/posts');

const { index, create, show, update, destroy } = require('../controllers/posts');

const route = express.Router();

/*
route('/').get(index).get();
route('/:id').get(show).get();
route('/').get(create).post();
route('/:id').get(update).put();
route('/:id').get(destroy).delete();
*/

route('/')
    .get(index)
    .post(create);

route('/:id')
    .get(show)
    .put(update)
    .delete(destroy);

module.exports = route;


controllers/posts.js
exports.index = ((req, res, next) => {
    res
        .status(200)
        .json({ success: true, message: 'index' })
})

exports.show = ((req, res, next) => {
    res
        .status(200)
        .json({ success: true, message: `show ${ req.params.id }` })
})

exports.create = ((req, res, next) => {
    res
        .status(200)
        .json({ success: true, message: 'create' })
})

exports.update = ((req, res, next) => {
    res
        .status(200)
        .json({ success: true, message: `update ${ req.params.id }` })
})

exports.destroy = ((req, res, next) => {
    res
        .status(200)
        .json({ success: true, message: `destroy ${ req.params.id }` })
})

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question