Routes for Express are throwing a 500 internal server error

My server is unable to locate the APIs that I have created in the API directory, which is resulting in a 500 internal server error.

I have thoroughly checked routes.js and everything appears to be correct. Additionally, I have an error.js file for handling errors. Below is my code:

'use strict';

let router = require('express').Router();

// Middleware
let middleware = require('./controllers/middleware');
router.use(middleware.doSomethingInteresting);

// Tasks
let tasks = require('./controllers/tasks');
let createkeypairs = require('./controllers/createkeypairs');
let importaddress = require('./controllers/importaddress');
let getwalletinfo = require('./controllers/getwalletinfo');

router.get('/tasks', tasks.findAll2);
router.get('/createkeypairs', createkeypairs.findAll);
router.get('/importaddress', importaddress.findAll);
router.get('/getwalletinfo', getwalletinfo.findAll);
router.post('/buggyroute', tasks.buggyRoute);



// Error Handling
let errors = require('./controllers/errors');
router.use(errors.errorHandler);

// If request was not picked up by any route, send 404
router.use(errors.nullRoute);

// Export the router
module.exports = router;

Now I will show you my createkeypairs.js file:

'use strict';

let errors = require('./errors.js');
var request = require("request");
var options = { method: 'POST',
    url: '127.0.0.1:18332',
    headers: 
    {  'Authorization': 'Basic bXVsdGljaGFpbnJwYzpHTmJ5enJhMnlHRjN4Ymp1cnluRTFucTlnV1ExRXV3OTFpYVBqSkt5TkJxdA==',
    'cache-control': 'no-cache',
    'Cache-Control': 'no-cache',
    'Content-Type': 'application/json' },
    body: { method: 'createkeypairs', params: [], chain_name: 'tokenchain' },
    json: true };

exports.findAll = (req, res, next) => {
// Simulate task list, normally this would be retrieved from a database
let createkeypairs ;
request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log("working here ");
    // res.json(body);

});

};

exports.buggyRoute = (req, res, next) => {
    // Simulate a custom error
    next(errors.newHttpError(400, 'bad request'));
};

Answer №1

It seems like the issue lies within the createkeypair file.

Feel free to try out this updated code snippet for your createkeypairs.js:

'use strict';

let errors = require('./errors.js');
var request = require("request");
let config = require('config');

var auth = 'Basic ' + Buffer.from(config.user + ':' + config.pass).toString('base64');
var url = config.url;
var chain = config.chain;

var options = { method: 'POST',
    url: url,
    headers: 
     { 'cache-control': 'no-cache',
            Authorization : auth,
         'Content-Type': 'application/json' },
    body: { method: 'importaddress', params: ["address"], chain_name: chain },
    json: true };

exports.findAll = (req, res, next) => {
    // Simulate task list, normally this would be retrieved from a database
    let createkeypairs ;

request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
    res.json(body);
});
};

exports.buggyRoute = (req, res, next) => {
    // Simulate a custom error
    next(errors.newHttpError(400, 'bad request'));
};

Please let me know if this resolves the issue.

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

Reduce the amount of time it takes for a Google AdWords Script to generate a

According to Google Script best practices, it is recommended to store operations in an array and then call the methods once all the operations have been constructed. This helps minimize response time each time a service is called. For example, let's ...

Totally clueless when it comes to JSON

After diving into tutorials on JSON, the structure and syntax are finally clicking for me. However, I'm currently working on a project that requires a GET, and it seems like JSON could help with this. I've come across comparisons of JSON and AJA ...

The calendar on the datetime picker is malfunctioning and not displaying any dates

The date and time picker feature appears to be malfunctioning on my website. I suspect it may be due to a conflict between the full calendar and gull admin theme that I am using. I have attempted various solutions but nothing seems to be working. How can ...

What is causing the button within my ExtJS grid to display as "[object Object]"?

Within an ExtJS grid, I am facing a scenario where I need to display a button in a specific column when the content of a cell meets certain criteria. To achieve this, I define the column with the button using a rendering function as shown below: { he ...

Preventing runtime error in Next.js API routes by handling axios exceptions

I am currently working on creating an API route in Next.js that sends a request to my backend and saves the token in the cookies. However, I am facing an issue where 4xx responses are causing an Unhandled runtime error. Despite everything working correctly ...

How can data be shared across different JavaScript functions?

I have two dropdown lists where I'm trying to pass the selected values for both to another function. I know that the way I am currently doing it is not correct, but I have been staring at this code for so long that I can't seem to find the probab ...

How can you temporarily stop an event with a click or touch, and then resume the event's state after performing certain tasks in jQuery?

Exploring options for tracking clicks with precision - interested in finding a way to defer the event propagation until a certain function completes. Any suggestions on an alternative approach or how to effectively delay the normal event flow? $(this).on ...

Express-session is failing to return a value in spite of my explicit declaration of the session

I've been working on my website for quite some time and everything was smooth sailing, until now. Here's the issue: after a user logs in, a session cookie named "user" is created to store their email. Upon console logging the cookie right after ...

Arrange the table by adding and editing before and after appending

I have a table data that needs to be dynamically appended. But I want to allow users to add new data using text input and also edit the existing data before and after it's appended. The problem is that when I append new data, it overwrites the previo ...

Adjust the pagination page size based on the value in the Angular scope dynamically

My goal is to provide the user with the ability to adjust the number of rows displayed in a table. This feature is crucial for our web app, as it needs to be accessible on various devices and should allow users to customize their viewing experience to redu ...

`"error_message":"Failed to process request with status code 500","error_type":"ServerError","error_stack":"ServerError: Failed to process request with status code 500 ``

For my project, I needed to retrieve data from an open API using the following link. As per the documentation, the HTTP method required is POST and the Content-Type should be either "application/graphql" or "application/json". I implemented a node express ...

I need assistance with an issue on my Google Dev Console, as it keeps showing an error stating that ".getcontext is

Looking for some assistance here as my development console keeps displaying an error: Uncaught TypeError: canvas.getContext is not a function. Here is the problematic code snippet: `var canvas = document.createElement; var c = canvas.getContext("2d&qu ...

What method is the most effective for preloading images and stylesheets?

One of the main concerns I have is optimizing the load time of my website. I would like to preload images, style sheets, and scripts to ensure a faster loading speed and to prevent users from seeing images loading right before them. Can someone suggest the ...

Tips for swapping out text with a hyperlink using JavaScript

I need to create hyperlinks for certain words in my posts. I found a code snippet that does this: document.body.innerHTML = document.body.innerHTML.replace('Ronaldo', '<a href="www.ronaldo.com">Ronaldo</a>'); Whil ...

Executing a raw query within an express.js route using sequelize

I'm currently a beginner in using sequelize. I have a node.js project set up with sequelize cli and am attempting to execute a raw query within a "put" express route of my application. However, I keep encountering an error: Sequelize.query is not a ...

JavaScript - Two tables shown in parallel

Beginner coder seeking assistance! I am currently working on an application with two user input fields placed adjacent to each other. Clicking parse buttons next to these fields generates two separate tables. However, I need these tables to be displayed si ...

Guide to implementing a slider in HTML to adjust the size of my canvas brush

Hey there, I'm looking to implement a slider functionality under my canvas that would allow users to change the brush size. Unfortunately, all my attempts so far have been unsuccessful. Can anyone lend a hand? Much appreciated! <canvas i ...

Effortless integration of jQuery with Google Maps autocomplete feature

I've successfully implemented Google Maps Autocomplete on multiple input tags like the one below: <input class="controls pac-input" id="pac-input" type="text" onfocus="geolocate()" placeholder="Type custom address" /> To enable Google Maps au ...

Using a PHP variable to trigger the jQuery .show() function

I'm attempting to trigger jQuery .show() events based on PHP variables. Below is my PHP code (retrieved from a form submission on another page): $last_pic_displayed = trim($_POST["last_pic_displayed"]); if (strlen($last_pic_displayed) <= ...

Having trouble retrieving the default selected value using the index in Angular Material's mat-button-toggle functionality

I'm encountering an issue with setting the default value for a toggle button group. The code is simple and the toggle buttons are correctly fetching values from the index, but I can't seem to get one of them to be default selected. I tried settin ...