Macintoshuser_2
Macintoshuser_2

Reputation: 89

Getting 404 Not Found when trying to access Node/Express endpoint from client

I have a Node.js/Express REST API I have made to be accessed by a front end React app for an inventory management system to use for a garage sale. When trying to add a new Product, I try to access the POST route http://localhost:3001/api/new. However, when I try to access it, it retures a 404 Not Found error, despite being confident that I've done what has to be done for the route to be seen to the server, in order for the client to be able to fetch it. Could anyone shed some light on what I might be missing if anyting?

Accessing the endpoint from the client:

const addNewItemHandler = async () => {
    setIsLoading(true);
        
    const REQUEST_BASE_URL = "http://localhost:3001";
    const REQUEST_ROUTE    = "/api/new";
    const REQUEST_URL      = `${REQUEST_BASE_URL}${REQUEST_ROUTE}`;

    const REQUEST_CONFIG = {
        method: "POST",
        body: JSON.stringify({
            "productID": productID,
            "name": productName,
            "quantity": quantity,
            "price": parseFloat(`${priceDollar}.${priceCents.split("")[0]}${priceCents.split("")[1]}`)
        }),
        headers: {
            'Content-Type': 'application/json'
        }
    };

    try {
        await fetch(REQUEST_URL, REQUEST_CONFIG);
        setIsLoading(false);

        const currentItems = JSON.parse(localStorage.getItem('all-items'));
        const newItem = {
            id: productID,
            title: productName,
            quantity: quantity,
            price: parseFloat(`${priceDollar}.${priceCents.split("")[0]}${priceCents.split("")[1]}`)
        };

        localStorage.setItem('all-items', JSON.stringify([...currentItems, newItem]));

        history.push('/');
    } catch (err) {
        console.error(err);
        setIsLoading(false);
    }
};

server.js:

const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const sequelize = require('./db-config');
const apiRoutes = require('./routes/APIRoutes');

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

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept, Authorization'
    );
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
  
    next();
});

app.use('/api', apiRoutes);

sequelize.sync().then(result => {
    app.listen(3001, console.log("Staring on port 3001"));
}).catch(error => {
    console.error(error);
});

APIRoutes.js

const express = require('express');
const router = express.Router();
const controller = require('../controller/Controller');

router.get('/all-items', controller.allitems);
router.get('/search/:term', controller.search);
router.get('/summary', controller.viewSummary);

router.post('/api/new', controller.createNewProduct);

router.patch('/sell-item', controller.sellProduct);

router.delete('/delete-all', controller.deleteAllProducts);
router.delete('/delete/:id', controller.deleteProduct);

module.exports = router;

Controller.js

const Sequelize = require('sequelize');
const Product = require('../models/Product');
const SoldProduct = require('../models/SoldProduct');
const Op = Sequelize.Op;

const allItems = (request, response) => {
    // ...
};

const search = (request, response) => {
    // ...
};

const viewSummary = (request, response) => {
    // ...
};

const createNewProduct = (request, response) => {
    const { productID, name, quantity, price } = request.body;

    Product.create({
        productID: productID,
        name: name,
        quantity: quantity,
        price: price
    }).then(() => {
        response.json({ message: "Successfully created a new product" });
    }).catch(error => {
        response.json({ message: "Something went wrong" });
    });
};

const sellProduct = (request, response) => {
    // ...
};

const deleteAllProducts = (request, response) => {
    // ...
};

const deleteProduct = (request, response) => {
    // ...
};

exports.allitems          = allItems;
exports.search            = search;
exports.viewSummary       = viewSummary;
exports.createNewProduct  = createNewProduct;
exports.sellProduct       = sellProduct;
exports.deleteAllProducts = deleteAllProducts;
exports.deleteProduct     = deleteProduct;

Upvotes: 2

Views: 5719

Answers (1)

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

In server.js file, you mount all the routes in APIRoutes.js file to /api path:

app.use('/api', apiRoutes);

With this configuration, the URL should be: http://localhost:3001/api/api/new.

You can mount your routes to '/' path, then you can access your routes like you did.

app.use('/', apiRoutes);

or in the APIRoute.js file, you change from /api/new to just /new

router.post('/new', controller.createNewProduct);

Upvotes: 3

Related Questions