1

I have my own rest API, that internally calls an NLP API, for which I have to post some data on their URL. I am using needle to achieve this, but there's some error that I cannot catch, and my own api is returning 500 to the frontend.

Here is that part of my server.js code:

app.post('/api/get',function(req,res) {
  //console.log(req);
  console.log("here in post ");
  if(!req.body){
    return res.send(400);
  }
  //console.log(req.body.msg);
  var searchQuery =  req.body.msg;
  var options = { 'api-key' : '3080a0e0-1111-11e5-a409-7159d0ac8188' };

  needle.post('http://api.cortical.io:80/rest/text/keywords?retina_name=en_associative',searchQuery,options,function(err, resp){
    if(err){
      console.log('something went wrong :' + err);
    }
    console.log('Got :'+resp );
});

I reach here in post every time, but nothing after that. I am also curious that is this correct way to specify my api-key for the external API.

Thanks.

user000111181
  • 403
  • 7
  • 20

1 Answers1

1

if you are using express 4.x, I am not sure whether you configured your express server but you need install body-parser and add the following lines in your express configuration:

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

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

If you are using express 3.x version, you don't need to install body-parser:

var express = require('express');
var app = express();

app.use(express.json());
app.use(express.urlencoded());


Now regarding your post route I edited it a little bit:

var config = require('./config');

app.post('/api/get', function (req, res) {
  var searchQuery = {
    q: req.body.msg
  };

  var NEEDLE_API_KEY = config.needle.API_KEY;
  var NEEDLE_URL = config.needle.URL;

  var options = {
    'api-key': NEEDLE_API_KEY
  };

  needle.post(NEEDLE_URL, searchQuery, options, function (err, needleResponse) {
    console.log(err || needleResponse.body);
    res.json(err || needleResponse.body);
  });

});

So I added a new file called config.js for purposes of having a reference for all your api keys, urls of your third party services.

module.exports = {
  needle: {
    API_KEY: process.env.NEEDLE_API_KEY,
    URL: 'http://api.cortical.io:80/rest/text/keywords?retina_name=en_associative'
  }
};

So when you run your server at the console, you should pass setting a value to your global environment variable called NEEDLE_API_KEY:

NEEDLE_API_KEY=666 node app.js

So in this way you are not saving any keys on your source code, you are saving keys in global environment variables that available only on the server machine.

Wilson
  • 9,006
  • 3
  • 42
  • 46