2016-02-29 14 views
9


Sto provando a fare una richiesta al mio server JS nodo che accetta la chiamata post/put. I parametri che sto tentando di inviare con post call tramite chai non sono visibili sul server (req.body.myparam).
ho provato con richiesta post qui sotto, ma si è conclusa con risultati non: -
Richiesta messaggio via Chai

var host = "http://localhost:3000"; 
var path = "/myPath"; 
chai.request(host).post(path).field('myparam' , 'test').end(function(error, response, body) { 

e

chai.request(host).post(path).send({'myparam' : 'test'}).end(function(error, response, body) { 
codice

Nodo JS è il seguente: -

app.put ('/mypath', function(req, res){      //Handling post request to create league 
    createDoc (req, res); 
}) 


app.post ('/mypath', function(req, res){      //Handling post request to create league 
    createDoc (req, res); 
}) 

var createDoc = function (req, res) { 
    var myparam = req.body.myparam;         //league id to create new league 
    if (!myparam) { 
     res.status(400).json({error : 'myparam is missing'}); 
     return; 
    }  
}; 

Sopra codice va al myparam manca.

Per favore fatemi sapere qual è il modo migliore per fare lo stesso.
Grazie in anticipo.

+0

È possibile condividere il codice dell'endpoint? –

+0

Aggiornamento del codice. Per favore fatemi sapere se avete bisogno di qualsiasi altra cosa. –

+0

Non vedo 'league' definito da nessuna parte? – Derek

risposta

13

Nel modo in cui hai scritto, suppongo che tu abbia usato il pacchetto chai-http. La funzione .field() non funziona in chai-http. Un altro utente lo ha segnalato here e ha aperto un problema su github.

Ecco come si potrebbe scrivere:

.set('content-type', 'application/x-www-form-urlencoded') 
.send({myparam: 'test'}) 

Ecco il codice completo che successo passa i parametri al server:

test.js

'use strict'; 
var chai = require('chai'); 
var chaiHttp = require('chai-http'); 

chai.use(chaiHttp); 

describe('Test group', function() { 
    var host = "http://" + process.env.IP + ':' + process.env.PORT; 
    var path = "/myPath"; 

    it('should send parameters to : /path POST', function(done) { 
     chai 
      .request(host) 
      .post(path) 
      // .field('myparam' , 'test') 
      .set('content-type', 'application/x-www-form-urlencoded') 
      .send({myparam: 'test'}) 
      .end(function(error, response, body) { 
       if (error) { 
        done(error); 
       } else { 
        done(); 
       } 
      }); 
    }); 
}); 

server.js

'use strict'; 
var bodyParser = require("body-parser"), 
    express  = require("express"), 
    app   = express(); 

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

app.put ('/mypath', function(req, res){ //Handling post request to create league 
    createDoc (req, res); 
}); 

app.post ('/mypath', function(req, res){ //Handling post request to create league 
    createDoc (req, res); 
}); 

var createDoc = function (req, res) { 
    console.log(req.body); 
    var myparam = req.body.myparam; //league id to create new league 
    if (!myparam) { 
     res.status(400).json({error : 'myparam is missing'}); 
     return; 
    } 
}; 

app.listen(process.env.PORT, process.env.IP, function(){ 
    console.log("SERVER IS RUNNING"); 
}); 

module.exports = app; 
+0

Questo ha funzionato per me. È divertente perché i documenti dicono di usare il metodo .field() quando pubblicano i dati del modulo, ma forse questo non funziona se stai usando bodyParser in questo modo sul server? –

+0

come allegare un file in questo? So che questo è il codice .attach ('imageField', fs.readFileSync ('avatar.png'), 'avatar.png') Ma non sono sicuro di dove collegarlo – Kannan

3

Ho trovato due modi per risolvere il problema con lo req.body vuoto.

  1. body come dati del modulo

    .put('/path/endpoint') 
    .type('form') 
    .send({foo: 'bar'}) 
    // .field('foo' , 'bar') 
    .end(function(err, res) {} 
    
    // headers received, set by the plugin apparently 
    'accept-encoding': 'gzip, deflate', 
    'user-agent': 'node-superagent/2.3.0', 
    'content-type': 'application/x-www-form-urlencoded', 
    'content-length': '127', 
    
  2. body come application/json

    .put('/path/endpoint') 
    .set('content-type', 'application/json') 
    .send({foo: 'bar'}) 
    // .field('foo' , 'bar') 
    .end(function(err, res) {} 
    
    // headers received, set by the plugin apparently 
    'accept-encoding': 'gzip, deflate', 
    'user-agent': 'node-superagent/2.3.0', 
    'content-type': 'application/json', 
    'content-length': '105', 
    

In entrambi i casi che uso .send({foo: 'bar'}) e non .field('foo' , 'bar').

Il problema apparentemente non ha nulla a che fare con chai-http. È il problema di superagent. E chai-http utilizza superagent sotto il cofano.

superagent tenta di giocare Machine Learning e fare ipotesi per noi.Ecco ciò che il loro docs say:

Per impostazione predefinita le stringhe di invio imposterà il Content-Type a application/x-www-form-urlencoded

formati superagent sono estensibili, però da "JSON" e "forma" di default sono supportati. Per inviare i dati come application/x-www-form-urlencoded invoca semplicemente .type() con "form", dove il valore predefinito è "json".

request.post('/user') 
    .type('form') 
    .send({ name: 'tj' }) 
    .send({ pet: 'tobi' }) 
    .end(callback) 

chai-http più grande difetto è che non documentano il suo plugin correttamente. Devi cercare le risposte su Internet e non sulla pagina di GitHub chai-http dove deve essere.

+0

come allegare un file in questo? So che questo è il codice .attach ('imageField', fs.readFileSync ('avatar.png'), 'avatar.png') Ma non sono sicuro di dove collegarlo – Kannan