Encountering MySQL PUT and DELETE Error 500 when using Express and Axios

An unexpected project has landed in my lap, pieced together using tools that are unfamiliar to me. It utilizes Express, Bookshelf, and Axios to connect with a MySQL database. While the GET and PUT routes in Express seem to be functioning properly, issues arise with POST and DELETE requests resulting in error 500 responses.

Below are snippets of the routes I am working with (I've omitted additional routes that are operational):

import express from 'express';
import Points from '../models/points';

let router = express.Router();

// Successfully retrieves all points linked to a user within a specific session
router.get('/user/:user/session/:session', (req, res) => {
    Points.query({
        select: ['id', 'number', 'quadrant', 'level', 'title', 'category'],
        where: {sessionId: req.params.session, userId: req.params.user}
    }).fetchAll().then(point => {
        res.json({point});
    })
});

// Effectively adds a single point to the database
router.post('/', (req, res) => {
    const {sessionId, userId, number, quadrant, level, title, category} = req.body;

    Points.forge({
        sessionId, userId, number, quadrant, level, title, category
    }).save()
        .then(user => res.json({success: true}))
        .catch(err => res.status(500).json({error: err}));
});

// Struggles with updating an existing point (500 error)
router.put('/edit/:identifier', (req, res) => {
    Points.update({
        set: {title: req.params.title},
        where: {id: req.params.identifier}
    }), function (err, point) {
        if (err) {
            return res.send(err);
        }
        res.json({message: 'Updated'});
    };
});

// Fails to delete a point by id (500 error)
router.delete('/delete/:identifier', (req, res) => {
    Points.remove({
        id: req.params.identifier
    }), function (err, point) {
        if (err) {
            return res.send(err);
        } else {
            res.json({message: 'Deleted'});
        }
    };
});

export default router;

Additionally, here are the Redux actions associated with the aforementioned routes:

import axios from 'axios';


export function getPointsByUserAndSession(data) {
    return dispatch => {
        return axios.get('/api/points/user/'+data.user+'/session/'+data.session)
    }
}

export function addPoint(data) {
    return dispatch => {
        return axios.post('/api/points', data)
    }
}

export function editPointById(data) {
    return dispatch => {
        return axios.put('/api/points/edit/' + data.id)
    }
}

export function deletePointById(identifier) {
    return dispatch => {
        return axios.delete('/api/points/delete/' + identifier)
    }
}

Answer №1

To implement CORS, add the following code snippet:

 router.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, x-access-token');
  res.header('Access-Control-Allow-Methods', 'GET, POST,OPTIONS, DELETE, PATCH, PUT');
  next();
});

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

Navigating multiple paths at once in Node.js

When I access /quiz in my router, the goal is to render quiz.ejs and retrieve quiz data using doGetQuiz in order to display it within quiz.ejs I presume that I need to adjust my router in some manner... Here are the steps I have taken thus far: router.ge ...

A guide on renewing authentication tokens in the Nestjs framework

import { ExtractJwt, Strategy } from 'passport-jwt'; import { AuthService } from './auth.service'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common&apo ...

Executing a NodeJS function from a JavaScript function

I am working on a project involving Firebase and I am looking to connect a server-side function that can send an email to the client-side script. Below is my server-side index.js file: const functions = require('firebase-functions'); var nodema ...

Display a loading dialog for several asynchronous requests being made via AJAX

When making two asynchronous ajax calls, a loading dialog box is displayed for each call using the code below: jQuery('#msg_writter').show(); After a successful request, the loading dialog is hidden with the following code: jQuery('#msg_w ...

How to fill a dropdown list in NetBeans 7.1

I am looking to incorporate a combo box that is populated from a MySQL database in NetBeans 7.1. I attempted the following code implementation, but unfortunately it did not work as expected. private void jComboBox1ActionPerformed(java.awt.event.ActionEven ...

Limiting the use of global variables or functions in Node.js

How can I restrict global variables and functions in Node.js? Similar to the 'require' method, I am looking to limit the use of the 'require' method. I do not want any Node applications to access "fs" in my custom Node framework buil ...

Customize the position of nodes and their descendants in a d3 tree chart by setting specific x and y coordinates

I am in need of a d3 tree structure that looks like this. https://i.sstatic.net/X6U3u.png There are two key points to understand from the image above: Headers will have multiple parents(wells). I need to be able to drag and drop links connecting w ...

How should one approach tasks that carry a risk of concurrency?

I need a solution for the following problem: function foo() { client 1 performs an update/delete // client 2 calls foo() and compromises data integrity client 1 performs an update/delete } What is the best approach to resolve this situation using M ...

nodemon is unable to locate the debug module

Trying to create a simple MEAN stack application using the express generator command. Managed to successfully run npm start and launch my app. However, encountering an error when trying to run nodemon. module.js:340 throw err; ^ Error: Canno ...

Determining the value of an object property by referencing another property

Upon running the code below, I encounter the following error message: Uncaught TypeError: Cannot read property 'theTests' of undefined $(document).ready(function() { var Example = {}; Example = { settings: { theTests: $(&apo ...

The dynamics between Express.js and MongoDB connections

I'm having trouble establishing a relationship between my tables, specifically when inserting a new character ("Personnage"). The error seems to occur only with the "ethnie" table and I'm not sure why. Any help or insight you can provide would b ...

Exploring the Origin of "props" in ReactJS

Currently, I am diving into the world of the official reactJS tutorial and you can find it here: https://reactjs.org/tutorial/tutorial.html#passing-data-through-props My journey with reactJS has been interesting so far, although there are still some parts ...

Accessing PHP output within Jquery

Even though I know PHP is a server-side script and JavaScript is client-side, I encountered an issue. I struggled to bypass browser security when making an AJAX request to another domain. Feeling lost, I decided to turn to PHP for help. The challenge I f ...

Challenges with browsing navigation in Selenium WebDriver

Recently, I began my journey of learning selenium WebDriver. In an attempt to automate the task of logging into an account using the Firefox browser, I encountered a discrepancy. Manually opening the browser and clicking on the login link from the homepag ...

`Count the number of rows needed to accommodate text line breaks within a div element`

Is there a method to determine the number of lines that text breaks into using the CSS property word-break: break-all? For example, if I have a div like this: <div>Sample text to check how many lines the text is broken into</div> And the corr ...

Using JavaScript to Generate Formatting Tags Based on User Selections from a Multiselect Dropdown

When a user selects formatting options (such as bold, italic, underline) from a multiselect dropdown, I need to generate corresponding formatting tags. For example, if the user selects bold and italic, I should create a tag like <b><i></i&g ...

Revisiting Angular: The Curious Case of an Object Attribute Altering Attributes on Two Separate Objects

Creating a website with Angularjs involves working with an array of objects: $scope.fieldsToShow = [ { "fields": {}, "type": "LOGGED_IN" }, { "fields": {}, "type": "PERSONAL", "user": 2, "name": ...

Adjusting the zoom level in leaflet.js ImageOverlay will cause the marker

Using ImageOverlay to display an image as a map with Leaflet.js, but encountering issues with marker positions shifting when changing the zoom level. Followed instructions from this tutorial, and you can find a code pen example here. // Code for markers ...

Reboot JavaScript once a day for optimal performance

Is it possible for the JavaScript's ?random to be based on the current date so that it only loads once a day? <script type="text/javascript" src="http://external.example.com/bookmarklet.js?random"></script> I am asking this question beca ...

What is the best way to connect my 'Projects' folder to app.js within a React application?

import "bootstrap/dist/css/bootstrap.min.css"; import Navbar from './components/Navbar'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Home from './components/Home'; import Project ...