The issue of receiving a 500 error when making a POST request in node.js

I have created my own unique REST API that utilizes an NLP API internally. I need to post data on their URL, but unfortunately I am encountering an error that is causing my API to return a 500 error to the frontend.

Below is a snippet 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 );
});

Although I always reach the point where it logs "here in post", nothing happens after that. I'm also unsure if I am correctly specifying my api-key for the external API.

Thank you.

Answer №1

When working with express 4.x, make sure to configure your express server properly and install body-parser. Add the following lines to 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 version 3.x, there is no need to install body-parser:

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

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


Regarding your post route, I made some edits:

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);
  });

});

I have introduced a new file called config.js for storing all your api keys and third party service URLs.

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

When running your server in the console, remember to set a value for your global environment variable named NEEDLE_API_KEY:

NEEDLE_API_KEY=666 node app.js

This way, you avoid saving any sensitive information in your source code and instead utilize global environment variables specific to the server machine.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing the insertion of a <div> element within an input field using jQuery

<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></scr ...

How can I make the background of a button change when I move my cursor over it

Is it possible to change the background image of a button when hovering over it? Perhaps have the image transition from left to right for a fading effect? Can this be accomplished? ...

Obtain the numerical value of the vertical position of the mouse (

Currently, I am coding a JavaScript game and my objective is to designate a variable specifically for the Y axis of the mouse. I kindly request that the code be kept as simple and straightforward as possible, avoiding unnecessary complexity. That conclud ...

Retrieving form parameters within an EJS template

Hey there! I'm diving into the world of Node.js on my own and hitting a stumbling block that seems simple but is causing me some serious frustration. Despite countless searches on Google, I can't seem to figure it out due to fatigue setting in. I ...

Leveraging route configuration's scope in HTML

As a beginner in AngularJs, I am currently exploring the creation of a single page application. However, I am encountering difficulties in converting my initial code into more professional and efficient code. During this conversion process, I have separate ...

The error occurs when Facebook and Twitter iframes are attempting to access and set 'document.domain'

When attempting to add Tweet and Facebook Like buttons to the project I'm working on, everything appears to be functioning properly. However, upon clicking the buttons, a JavaScript error occurs: Unsafe JavaScript attempt to access frame with URL htt ...

Discovering XMLHttpRequest Issues within a Chrome Application

Is there a way to identify XMLHttpRequest errors specifically in Chrome App? For instance, I need to be able to recognize when net::ERR_NAME_NOT_RESOLVED occurs in order to display an error message to the user. While XMLHttpRequest.onerror is activated, ...

Next.js Error: Unable to access the 'collection' property, as it is undefined

I have recently started using next.js and I am interested in creating a Facebook clone by following YouTube tutorials. However, I keep encountering the error message "Cannot read properties of undefined (reading 'collection')". To troubleshoot, I ...

What is the best way to store multiple forms in a single request using React?

Is there a more efficient way for me to save multiple forms in multiple child components from the parent component using just one API request? I have attempted to utilize Context and reducer, which did work. However, I am unsure if this is the best approa ...

Error: The use of "let" as a lexically bound identifier is not permitted

Currently working with vue.js and encountering the error message "Uncaught SyntaxError: let is disallowed as a lexically bound name". When trying to troubleshoot, I'm faced with a blank screen and this error appearing in the console. I've search ...

What is the process for refreshing HTML elements that have been generated using information from a CSV document?

My elements are dynamically generated from a live CSV file that updates every 1 minute. I'm aiming to manage these elements in the following way: Remove items no longer present in the CSV file Add new items that have appeared in the CSV file Maintai ...

Vercel deployment issue: Hidden input values not being detected as expected

Whenever I attempt to update the data on Vercel, an error message is displayed: invalid input syntax for type uuid: "undefined" - unable to save Oddly enough, the data updates successfully when done locally. This is how I submit the form: <form onSu ...

Unable to successfully upload a file in nestJS due to unreliable network conditions

I have successfully set up a controller with a route for file uploads using axios. The implementation includes utilizing FileInterceptor. Everything functions properly, however, when I enable network throttling in the browser, the uploader ceases to work. ...

What are the pros and cons of passing an imported object from a parent component to its children as props versus directly importing that object within the children components?

My current project involves a helper object known as TimeHelper, which is used for time-related tasks. This object is required in multiple components within the top-level parent component. I am contemplating whether it would be advantageous to import Time ...

Adding labels to a JavaScript chart can be done by using the appropriate methods

https://i.stack.imgur.com/uEgZg.png https://i.stack.imgur.com/y6Jg2.png Hey there! I recently created a chart using the Victory.js framework (check out image 1) and now I'm looking to incorporate labels similar to the ones shown in the second image ab ...

Utilize the _sortBy function from the lodash library to arrange an array based on a specific field

Looking at an array of objects similar to this: myArray = [ {AType: "aaa", Description: "De", …}, {AType: "bbb", Description: "Hi", …}, {AType: "ccc", Description: "Un", …}, {AType: "ddd", Description: ...

What is the best way to display input fields only if the previous input has a valid value?

My challenge involves creating a form with 3 to 10 text input fields. Initially, the form will display only 3 inputs (minimum). I am looking for an efficient way to dynamically show additional input rows as each previous row is filled out with a valid val ...

Is the jquery autocomeplete plugin malfunctioning when using numbers in the input?

I encountered a requirement to display stock number suggestions within a search box. To achieve this, I decided to implement the Jquery autocomplete plugin. Through an ajax call to a function in my cfc, I was able to retrieve all the stock numbers and stor ...

Exclude JSON Property if it Lacks a Certain Value

I'm attempting to retrieve specific values from a DynamoDB database where the name is "john". The challenge I'm facing is that although I can fetch values containing name: john from a mapped list, I also receive additional unwanted values. When ...

Validator alert for AMP scripts

I have implemented the amp version for my content management system. Since each article has a different body, some include amp-instagram while others include amp-facebook, and so on. In order to cover all bases, I have added both amp-facebook and amp-inst ...