简体   繁体   中英

NodeJS - Why POST after GET doesn't work in express app?

This is app have only GET /test , it doesn't have POST /test yet. I'm uploading binary file 1.dat to it and it should return answer with '404', but seems I'm recieving ECONNRESET error instead.

var express = require('express');
var app = express();
var expect = require('expect.js');
var request = require('supertest');

var router = express.Router({
    caseSensitive: true,
    strict: true
});
router.get('/', function(req, res, next) {
    res.send('test');
});

app.use('/test', router);

app.use(function(req, res, next) {
    res.send('404');
});

Promise.resolve().then(function() {
    var agent = request(app);
    return new Promise(function(resolve, reject) {
        agent
            .get('/test')
            .expect(200)
            .end(function(err) {
                if (err) {
                    return reject(err);
                }
                resolve(agent);
            });
    });
}).then(function(agent) {
    return new Promise(function(resolve, reject) {
        agent
            .post('/test')
            .attach('tmp', new Buffer([1, 2, 3]), '1.dat')
            .expect(404)
            .end(function(err, res) {
                if (err) {
                    return reject(err);
                }
                resolve();
            });
    });
}).then(function() {
    process.exit(0);
}).catch(function(err) {
    console.log(err.stack);
    process.exit(1);
});

But why it throws an error when validating .expect(404) :

[TypeError: Cannot read property 'status' of undefined]

You don't send a status 404 but a string in your body.

app.use(function(req, res, next) {
  res.status(404).end();
});

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