Api работали 5 минут a go, но теперь они хотели d ie и даже не отвечают, только 404 - PullRequest
0 голосов
/ 20 июня 2020

Я работаю в качестве внешнего разработчика, но в целом новичок от ie до node.js, express и MongoDB. Хотел выучить его просто для каких-то хобби-приложений. Так или иначе, вот файлы:

server. js file

const express = require('express'); 
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');

const app = express();
const port = 8000;

app.use(bodyParser.json());

MongoClient.connect(db.url, ({ useUnifiedTopology: true }),
    (err, base) => {
        if (err) {
            return console.log(err)
        }
        // Make sure you add the database name and not the collection name  
        const database = base.db("kingdom-light")
        require('./routes')(app, database)
    });

app.listen(port,
    () => {
        console.log('We are live on ' + port);
    });

db. js file

module.exports = {  url : "mongodb://127.0.0.1:27017" }; 

index. js

 const noteRoutes = require('./note_routes');

module.exports = function (app, db) {
    noteRoutes(app, db);  // Other route groups could go here, in the future
};

note_routes. js

    //QUESTA PAGINA FA LA STESSA COSA DELLA PARTE CONTROLLER DI SPRING
var ObjectID = require('mongodb').ObjectID;

module.exports = (app, db) => {
    app.get('/notes/:id', (req, res) => {
        const details = {
            '_id': ObjectID(req.params.id)
        }; //VISTO CHE L'ID è UN OGGETTO OBJECT ID CONVERTE IL COSO IN OGGETTO
        db.collection('notes').findOne(details, (err, item) => {
            if (err) {
                res.send({ 'error': 'An error has occurred' });
            } else {
                res.send(item);
            }
        });
    })
};

module.exports = function (app, db) { 
    app.get('/notes', (req, res) => {
        db.collection('notes').find({}, (err, result) => {
            if (err) {
                res.send({ 'error': 'An error has occurred' })
            } else {
                res.send(result);
            }
        });
    });
};

module.exports = function (app, db) { //FUNCTION E ARROW FUNCTION SONO UGUALI, COME SI VEDE
    const collection = app.post('/notes', (req, res) => {
        const note = { text: req.body.body, title: req.body.title };
        db.collection('notes').insert(note, (err, result) => {
            if (err) {
                res.send({ 'error': 'An error has occurred' })
            } else {
                res.send(result.ops[0]);
            }
        });
    });
};

module.exports = (app, db) => {
    app.delete('/notes/:id', (req, res) => {
        const id = req.params.id;
        const details = {
            '_id': new ObjectID(id)
        }; db.collection('notes').remove(details, (err, item) => {
            if (err) {
                res.send({ 'error': 'An error has occurred' });
            } else {
                res.send('Note ' + id + ' deleted!');
            }
        });
    })
};

module.exports = (app, db) => {
    app.put('/notes/:id', (req, res) => {
        const id = req.params.id;
        const details = {
            '_id': new ObjectID(id)
        }; 
        const note = { text: req.body.body, title: req.body.title };
        db.collection('notes').update(details, note, (err, result) => {
            if (err) {
                res.send({ 'error': 'An error has occurred' });
            } else { 
                res.send(note);
             }
        });
    })
};

Я думал, что это файл не загружается, но проверяется некоторыми console.logs, что это было. Поэтому я подумал, что проблема связана с слишком большим количеством API-интерфейсов в маршруте, прокомментировал все, кроме одного ... все еще не работал. Обращаюсь за помощью!

...