I am using SuperAgent to test a Node/Express REST API.
Using .send, the body content is automatically converted to JSON. I would like to send plain text only. Here is an example:
request.post('localhost:3000/api/compile' )
.send('my example text that gets converted to JSON')
.set('Content-Type', 'application/x-www-form-urlencoded')
I have tried changing the Content-Type header, but still an object is sent.
How can I force SuperAgent to use plain text only?
UPDATE 1: Adding .type('form') as suggested still defaults to JSON.
request.post('localhost:3000/api/compile' )
.type('form')
.send('my example string')
.set('Authorization', un+':'+key)
//.set('Content-Type', 'application/x-www-form-urlencoded')
.end(function(err, res){
res.should.have.status(200);
done();
});
This gives -
object
{ 'my example string': '' }
UPDATE 2: Adding backend code. Could this simply be Express?
app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/api', api);
Route:
router.post('/compile', function(req, res) {
console.log(typeof(req.body));
console.log(req.body);
res.send('respond with a resource');
res.end();
});
SOLUTION - remove BodyParser:
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded());
app.use (function(req, res, next) {
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.rawBody = data;
next();
});
});
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/api', api);