问题描述:

In util/index.js I have these methods:

'use strict';

const parser = require('body-parser');

const express = require('express');

const app = express();

const RtmClient = require('@slack/client').RtmClient;

const RTM_EVENTS = require('@slack/client').RTM_EVENTS;

const db = require('../db').db;

const rtm = new RtmClient(process.env.SLACK_API_TOKEN);

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

rtm.start();

let POST = (url, handler) => {

app.post(url, (req, res) => {

handler(req)

.then(data => {

res.status(200).send(data);

})

.catch(error => {

res.status(500).send('Error: ' + error.message || error);

});

});

};

let setStatus = url => {

POST(url, req => db.users.insert({

username: req.body.user_name,

userid: req.body.user_id,

status: url.toUpperCase()

}));

};

module.exports = {

POST,

setStatus

};

And in my project/index.js, I call them like this:

'use strict';

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

const db = require('./db').db;

const express = require('express');

const app = express();

const u = require('./util');

u.POST('/logdash', () => db.users.select());

u.setStatus('here');

u.setStatus('out');

u.setStatus('break');

u.setStatus('left');

u.setStatus('sick');

u.setStatus('hungry');

app.listen(port, () => {

console.log('Server is now running on port ' + port);

});

But then I get Cannot POST /[route]. This is a Slack app, and before transferring those two methods into another file, it was working nicely. I yet don't quite understand Node.js, for this is my first app I ever make. I'm used to programming languages like PHP, but then, by doing the same conventional way for method separation into different files, this error is thrown for me.

I believe the issue is in POST method, because it displays a message in the channel when a route is accessed and the database operation is done, but I probably need to do something different when requiring it from another file.

网友答案:

Thanks to @SLaks comment, I could think and figured out.

First, I've exported app, required and started it like this:

u.app.listen(port, () => {
    console.log('Server is now running on port ' + port);
});

The other problems were simply because of a missing '/' before the url parameter in setStatus method:

let setStatus = url => {
    POST('/' + url, req => db.users.insert({
        username:   req.body.user_name,
        userid:     req.body.user_id,
        status:     url.toUpperCase()
    }));
};
相关阅读:
Top