Attempting to locate by ID, however, the server is failing to provide the correct status response

  1. When attempting to use the Axios.get method to retrieve ':id', I am receiving a 404 error response from the server
  2. I am currently facing difficulties in setting the state of the component as it returns an empty object

I have made several adjustments to the controller parameters but still unable to resolve the issue

loadProfile() {
        axios.get('http://localhost:3000/api/companies/' + this.props.match.params.id)
            .then(res => {
                if (!res) {
                    console.log("404 error, axios cannot get response");
                } else {
                    console.log(res.data);
                    this.setState({ company: res.data });
                }
            });

Express API route

companyRoutes.route('/:id').get(company_controller.company_id_get);

Express controller

exports.company_id_get = (req, res) => {
    const id = req.params.id;
    Company.findById( id, (company, err) => {
        if(err) {
            console.log("404 error", err);
        }
        else {
            res.json(company);
        }
    })
}

Server Side Code


'use strict';

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors')
const passport = require('passport');

const app = express();
const users = require('./routes/api/users');
const companyRoute = require('./routes/api/companies');

app.use(express.static("static"));
//Bodyparser middleware

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

// DB configuration
const db = require("./config.scripts/mongoKey").mongoURI;

// Connect to MonngoDB
mongoose.connect(
    db, { useNewUrlParser: true }
)
    .then((db) => console.log('MongoDB succesfully connected'))
    .catch(err => console.log(err));

//Passport middleware
app.use(passport.initialize());

//Passport config
require('./config.scripts/passport.js')(passport);

//Routes
app.use('/api/users', users);
app.use('/api/companies', companyRoute);

//Redirect any server request back to index.html: To deal with CRS
app.get('/', function(req, res, next){
    res.sendFile(path.join(__dirname, '../client', 'index.html'));
})

//Hostname and Port
//const hostname = '127.0.0.1';
const port = 3000;

app.listen(port, () => {
    console.log(`Backend server is running at http://localhost:${port}/`);
});

An error that is showing up in the console/network and postman. It looks like the http.get request is being stalled

Answer №1

It appears that you may have overlooked adding a / in your route

http:/localhost:3000/api/companies/...
. Simply update it to http://... and this should resolve the problem.

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

Shortening a jQuery If-Else Statement in JavaScript

I am working on a snippet of code and need some help. Here is the code: <script type="text/javascript"> $(window).load(function() { if(!$.browser.msie){ $('#myDiv').animate({opacity: 1}, 300); } else if ($.browser.msie) { ...

What is the best way to generate a composite unique auto-incrementing field in mongoose?

I have an idea for creating a schema that allows users to set a specific display name that can be shared by multiple people. This involves saving the name in a model with two fields - one for the name itself and another for an ID representing the number of ...

Changing Images with Button Click in Javascript

I am facing an issue with my buttons that should swap images once clicked. The first two buttons work perfectly, but for the third and fourth buttons, the images do not disappear when clicking another button. Below is the current code in the document head ...

Are mutations in Vuex guaranteed to be atomic?

I'm currently investigating the atomicity of mutations in Vuex. The code snippet I'm reviewing has me questioning whether the CHANGE_A mutation could potentially be triggered while CHANGE_B is still in progress: const mutations = { [CHANGE_A]( ...

Can you provide an explanation of MONGO_URL and its correct configuration value?

After downloading some code from GitHub to experiment with on my local machine, I encountered MongoDB for the first time. Following the instructions from this website, I successfully downloaded MongoDB and ensured it was running using the sudo service mong ...

Nodemon isn't functioning properly: nodemon isn't loading as expected

db.js const mongoose = require('mongoose'); const mongoURI = "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false"; const connectToMongoDb = ()=>{ mongoose.connect(mongoURI, ()=>{ ...

Passing JSON data from an Angular.js frontend to a Node.js backend is

Whenever I try to send a JSON object from my angular.js frontend to the node.js backend, I keep getting this error message: TypeError: Cannot read property username of undefined. I am also using Express in my project. Frontend (Angular.js): var username_ ...

What is the reason behind using AJAX to attempt sending a new URL request on

Having a strange issue with my product list. When trying to edit a product by clicking on it, I am redirected to the product form where an AJAX request is supposed to be sent to getFiltersGroup. However, on error, the AJAX request is somehow being sent to ...

Updating the style sheet of a selected menu item on an ASP.NET master page

I created an asp.net master page with a menu setup like this: <menu id="menu"> <nav id="main_nav"> <ul id="menu-primary"> <li ><a href="./">Home</a></li> <li><a href="staff.aspx"& ...

What is the best way to assign multiple events and handlers using the .on method?

I've been attempting to move a submenu using multiple handlers within the on method. My goal is to trigger the function panelON when the mouse enters one of the li elements, and execute the function panelOFF when the mouse leaves it. I have tried dif ...

Sort the best match result at the top and display the rest of the results in sequential order

I am currently working on developing a city filter using mongodb and nodejs. The filter will consist of a list of cities with checkboxes, as shown below: city name 1 city name 2 city name 3 city name 4 When a user clicks on one or multiple cities, the d ...

Struggle with dynamically placing Checkboxes in the right spots

When trying to create dynamic CheckBox elements, I encounter issues with positioning them correctly. I aim to place them below the input field instead of below the Image. However, I am unsure of how to achieve this specific placement. Demo HTML: <di ...

Node.js requires password authentication for accessing a secure route

I need to implement additional security measures for my admin user accessing a specific route. Even though the user is already logged in, I want to require them to re-enter their password before accessing this route. How can I incorporate this into my ex ...

What is the best way to call the index.js file of a node located outside the /src folder in a MERN application?

As I near completion of my first MERN app, I encountered an issue retrieving data from MongoDB to populate my Autocomplete search bar. Although I found a tutorial for nodejs+express that explains how to retrieve the data from the database, it is limited on ...

Refresh the page with user input after a button is clicked without reloading the entire page, using Python Flask

My python/flask web page accepts user input and returns it back to the user without reloading the page. Instead of using a POST request, I have implemented Ajax/JavaScript to handle user input, process it through flask in python, and display the result to ...

Spacing is missing between Months and Years in the Bootstrap Datepicker

Currently, I am utilizing the Bootstrap Date picker plugin from . In their example, they showcase a grid-style format with spacing between the months and years that appears quite visually appealing. However, when implementing their JavaScript and CSS file ...

Within Node/Express, when accessing req.query.token, it returns as undefined when navigating to localhost:3000/?token=foobar

I'm facing an issue with parsing a URL in my Express backend. Whenever I visit a url like localhost:3000/token=myJwtToken, the value of req.query.token in my backend middleware authJwt.verifyToken is coming up as undefined. In my React App.js, I am m ...

Ways to stop a JS plugin affecting HTML anchors and preventing them from automatically scrolling to the top

My friend is working on a website and he's using a plugin called Flip Lightbox. The basic functionality of the plugin is that when you click on an image, it flips over and pops out as a lightbox. Everything works fine, however, if you scroll down the ...

When attempting to start a new React Native project using npx, I encountered an error stating "react-native: command not found"

After running 'npx react-native init MyProject' for the first time, it prompted that react-native would be downloaded, but I mistakenly terminated the process. Now, when I try again, it shows an error saying 'react-native: command not found& ...

Use jQuery to easily add and remove rows from a table dynamically

Is there a way to dynamically add rows to an HTML table using jQuery by utilizing a popup window? The popup would contain text fields, checkboxes, radio buttons, and an "add" button. Upon clicking the "add" button, a new row would be added to the table. ...