2017-05-29 73 views
1
// call the packages 
var express = require('express'); 
var app = express(); 
var bodyParser = require('body-parser'); 
var figlet = require('figlet'); 
var querystring = require('querystring'); 
var http = require('http'); 
var fs = require('fs'); 
var request = require('request'); 

// configure app to use bodyParser() 
// this will let app get the data from a POST 
app.use(bodyParser.urlencoded({ 
    extended: true 
})); 
app.use(bodyParser.text()); 

// set port 
var port = process.env.PORT || 8082; 

// get an instance of the express Router 
var router = express.Router(); 


// middleware to use for all requests 
router.use(function(req, res, next) { 

    // do logging 
    console.log('UnitGener router invoking'); 
    // go to the next routes and don't stop here 
    next(); 
}); 

// test route to make sure everything is working (accessed at GET http://localhost:8082/api) 
router.get('/status', function(req, res) { 
    res.json({ 
     message: 'UnitGener is ready to work!' 
    }); 
}); 


//noinspection JSUnresolvedFunction 
router.route('/function') 

    .post(function(req, res) { 
     console.log(req.body); 
     var formatted = req.body; 


     request.post({ 
      headers: { 
       'content-type': 'application/x-www-form-urlencoded' 
      }, 
      url: 'http://localhost:5000/generate', 
      body: formatted 
     }, function(error, response, body) { 
      console.log(body); 
     }); 

    }); 

app.use('/api', router); 
app.listen(port); 
}); 

这里是我的创建与给定CONFIGS一个POST路线,然后我打电话POST方法中的另一布线后完整的代码。但我得到“抛出新的TypeError('第一个参数必须是字符串或缓冲区');”这个错误。我做了一些谷歌发现,并做了一些改变,也没有工作,仍然觉得很难指出错误。我改变了身体:格式化为body:formatted.toString()也没有工作。请给我一些建议来找出答案。它对我来说是一个巨大的帮助。获得“第一个参数必须是一个字符串或缓冲区”错误

由于提前

回答

0

你为什么写:

router.route('/function') 
    .post(function(req, res) { 

尝试:

router.post('/function', function(req, res) { 
+0

给出同样的错误:( – Cyrex

3

的错误是在请求调用。提交表单正确使用

request.post({ 
     url: 'http://localhost:5000/generate', 
     form: formatted 
    }, function(error, response, body) { 
     console.log(body); 
    }); 

我鼓励您使用NPM模块请求承诺本机: https://github.com/request/request-promise-native https://www.npmjs.com/package/request-promise

var rp = require('request-promise'); 

var options = { 
    method: 'POST', 
    uri: 'http://api.posttestserver.com/post', 
    body: { 
     some: 'payload' 
    }, 
    json: true // Automatically stringifies the body to JSON 
}; 

rp(options) 
    .then(function (parsedBody) { 
     // POST succeeded... 
    }) 
    .catch(function (err) { 
     // POST failed... 
    }); 
2

你的身体预计将缓冲试试这个,JSON:请求选项

request.post({ 
     headers: { 
      'content-type': 'application/x-www-form-urlencoded' 
     }, 
     url: 'http://localhost:5000/generate', 
     body: formatted, 
     json:true 
    }, function(error, response, body) { 
     console.log(body); 
    }); 
+0

谢谢!我遇到了这个问题,并添加了请求选项中的“json:true”是需要修复的。非常感激。 –

相关问题