Text processing / plain in Express (via connection)?

I am using Express 3 and would like to handle POST text / plain files .

Express 3 now uses connect bodyParser (I think the old Express code has been moved to connect). The documentation for bodyParser provides some information on how to get it to support additional file types. And I found a great blog post about how / plain text processing was done in older versions of Express ).

  • Should I explicitly require a connection (and let node require a modified version cache)? Or can I connect via express somewhere?

  • connect.bodyParser does not have a parsing key.

How can I make Express (via connect) text / simple POST messages?

+5
source share
5 answers

With bodyParser as a dependency, add this to your app.jsfile.

var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.text());

Happy coding.

+14
source

https://gist.github.com/3750227

app.use(function(req, res, next){
  if (req.is('text/*')) {
    req.text = '';
    req.setEncoding('utf8');
    req.on('data', function(chunk){ req.text += chunk });
    req.on('end', next);
  } else {
    next();
  }
});

Text will be added as req.text

+21
source

, json.js , buf - . plain.js, " " . , . , , - , node.

+2

express.js "^ 4.16..." :

// parse an HTML body as a string
app.use(bodyParser.text({ type: 'text/*' }))

:

// parse an HTML body as a string
app.use(bodyParser.text({ type: 'text/*' }))

// Enable CORS for ExpressJS
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS')
  res.header('Access-Control-Allow-Credentials', true)
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Methods, Credentials')
  next()
})


// Api url 
app.post('/api/myApi', (req, res) => {

  const bodyJson = JSON.parse(req.body)
  // do something

}
0

:

var expressApi= (req, res,params)=>{
    console.log('req.body',params);
    var body = '';
    req.on('data', function (data) {
        body += data;
    });
    req.on('end', function () {
        res.write({status:200,message:'read data'}); 
    }); 
}
0

All Articles