Handling text/plain in Express (via connect)?
With bodyParser as dependency, add this to your app.js
file.
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.text());
Happy Noding.
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();
}
});
Will add the text as req.text
In express.js "^4.16..." the following code works fine for me:
// parse an HTML body as a string
app.use(bodyParser.text({ type: 'text/*' }))
The extended piece of the code is below:
// 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
}