Troubleshooting Error 405 in AJAX, Javascript, Node.js (including Body-Parser and CORS), and XMLHttpRequest

I have been working on creating a JSON file from buttons. While I am able to retrieve data from the JSON files that I created, I am facing issues with posting to them using XMLHttpRequest and Ajax. Interestingly, I can add to a JSON file using routes just by using the URLs alone, but I'm struggling to figure out how to set up a route for the following code.

No matter what I try, I keep encountering a '405 error message - Method Not Allowed'. I have already granted permission for the site through Google Chrome Settings Security and have installed all necessary packages like NPM Cors and Body-Parser.

What am I missing that is causing the 405 error to persist? Do I need to create a specific route for adding data, similar to what is used for a form?

Any help or advice on this issue would be greatly appreciated. Thank you!

In my Server.js:

var express = require('express');
var app = express();
var bodyParser = require('body-parser')
var cors = require("cors");

// PORT CONNECTION
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`Server Port: ${PORT}`);
});

//PUBLIC FOLDER
app.use(express.static('public'));

// parse application/json
var jsonBP = app.use(bodyParser.json());

app.use(function (req, res) {
    res.setHeader('Content-Type', 'application/json');
});

// POST /api/users gets JSON bodies
app.post('/api/actions', jsonBP, function (req, res) {
    buttons.response // not sure what this line does?
});

//CORS
app.use(cors());

Javascript snippet:

for (i = 0; i < facialExpressions.length; i++) {
    var CreateButton = document.createElement("button");
    var section = "Facial Expressions";
    CreateButton.innerText = facialExpressions[i];
    document.getElementById("facial").appendChild(CreateButton);
    CreateButton.addEventListener("click", function (e) {
        e.preventDefault();
        var params = JSON.stringify({
            action: this.innerHTML,
            date: Date(),
            section: "Facial Expressions",
            videoID: videoID,
            username: username
        });

        console.log(params);

        xhr.open("post", "./db/actions.json", true);
        xhr.setRequestHeader("Content-Type", "application/json");
        console.log('READYSTATE: ', xhr.readyState);
        xhr.onreadystatechange = () => {
            if(xhr.readyState == 4 && xhr.status ===201){
                let object = JSON.parse(xhr.response);
                console.log(object);
            }
        }

        xhr.send(encodeURIComponent(params));

    });
}

HTML code fragment:

</br></br>
<p id="status"></p>
    <table>
        <tr>
            <td width="10%">
                <h3>Facial Expressions</h3>
            </td>
            <td width="50%">
                <h3>Video</h3>
            </td>
            <td width="40%">
                <h3>Physical Actions</h3>
            </td>
        </tr>
        <tr>
            <td>
                <div id="facial"></div>

            </td>
            <td>

                <div id="videoPlayer"></div>
                <div>
                    <button id="start">Start</button>
                </div>
            </td></tr>
            <tr>
            <td colspan="3">
                <div id="actions"></div>
            </td>
        </tr>
        </tr>
    </table>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="../script.js"></script>

Answer №1

It dawned on me that the solution was to establish a route/REST API. This simple action enabled me to successfully circumvent the 405 error.

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

Encountering a problem when looping through a JSON response

After making an Ajax call, I received the JSON response below. studentList: { "currentStudent":0, "totalStudent":11, "studentDetails": [{ "adId":1, "adName":"BMB X5", "sfImage":{ "imageName":"Desert", "image ...

Checking the image loading functionality with Cypress

I am interested in testing Cypress to verify that an image is successfully loaded onto a page. Here is a snippet of my source code: import React from "react"; export default class Product extends React.Component { render() { return ( <div ...

What is the mechanism behind image pasting in Firefox's imgur integration?

Start by launching an image editing software and make a copy of any desired image. Avoid copying directly from a web browser as I will explain the reason later on. Navigate to "http://imgur.com" using Firefox. To paste the copied image, simply press Ctrl+V ...

Employing ajax for handling a request from a dynamically created roster

I'm encountering an issue with deleting records from a database using a PHP loop. I want to remove records without having to refresh the page, but I'm struggling to implement this feature. Currently, I have a span element (styled as a bootstrap ...

Leveraging the power of the three.js library on the client-side within a vue.js/n

I'm facing a challenge with incorporating the three.js library (installed via npm) to display 3D models on the client side within my nuxt.js application. Despite multiple attempts, I seem to be hitting a roadblock with the import not functioning prope ...

Utilize React without integrating a router component

For my web application built with reactjs, I am considering creating a multi-page site rather than a single page. Should I bundle all the react code into one file and include it on every page of the application, then utilize the exposed function to render ...

Create an animation effect where a div increases in height, causing the divs beneath it to shift downward in a

My aim is to create columns of divs where the user can click on a div to see more content as the height expands. I've managed to set this up, but it seems there's an issue with the document flow. When I click on a div in the first column, the div ...

PHP and AJAX allow for seamless data retrieval without the need for page refreshing, and the data can be easily displayed in a modal window

I am currently encountering an issue with sending data to another page without refreshing. I am able to send the data as text, but for some reason, I am unable to send it as a modal. Why might this be happening? Here is an image of my current page https:/ ...

What issues can arise in JavaScript if the URL length is not zero when there is no match found?

Upon clicking the "Open Windows" button in Code A, I expected the two links to open in two tabs simultaneously in Chrome, which is exactly what happened. However, when I added a blank line in the textarea control in Code B, only the link http:// ...

How to dynamically add variables to object paths using JavaScript and Angular

I've been struggling to grasp this concept, despite hours of searching. My goal is to dynamically generate form fields based on a user-selected 'type' from a dropdown menu. This will be linked to the variable "currentType" in Angular, which ...

What is the best approach to determine the numerical equivalents of options in a dropdown menu using PHP and JS

Hey guys, I'm really stuck on this problem and I can't seem to find a helpful tutorial anywhere. I've got a form with two drop-down menus, each with a "value" attribute. What I want is for users to be able to select an item from both drop-do ...

Showing off HTML tags within react-json-tree

I have incorporated the following npm package into my project: https://www.npmjs.com/package/react-json-tree My goal is to showcase a json tree in react, but I am facing a challenge on how to include an HTML tag as a JSON value. Are there any alternative ...

Processing a JSON array of objects in AngularJS

When using Angular's fromJson function to parse a JSON string, I encountered an issue. If the JSON is a simple array like "[1, 2]", the code works fine. However, I need to work with an array of dictionaries instead. var str = "[{'title' ...

What is the process for running an older Angular project using ng serve?

I'm currently attempting to run a sample Angular project that is part of a third-party framework by using the command ng serve. It seems like this sample project requires Angular version ~4 based on the information in its package.json file. My global ...

Developing a dynamic web application using the Django framework along with the Vue.js library and Highcharts for

I am currently working on a data visualization web app using Django, Highcharts, and JQuery. I have recently transitioned from JQuery to Vue JS and I am struggling with fetching JSON data from a specific URL. Below is the code snippet: Template <!doc ...

Tips for establishing communication between a React Native webView and a React web application

I am currently working on establishing communication between a webView in react-native and a web-app created with React-360 (and React). I am utilizing the react-native-webview library and following a guide for creating this communication. You can find the ...

What exactly is the purpose of editing a host file?

After reviewing this repository, an automatic message pops up: Don't forget to modify your host file 127.0.0.1 * http://localhost:3001 What exactly does that entail? ...

Swipe to modify Array

Currently, I am in the process of developing an application that features a Swipe card interface using both AngularJS and the Ionic framework. The functionality of this app will be similar to the one found at . When swiping to accept a card, I want the ar ...

Looking to retrieve the full browser URL in Next.js using getServerSideProps? Here's how to do

In my current environment, I am at http://localhost:3000/, but once in production, I will be at a different URL like http://example.com/. How can I retrieve the full browser URL within getServerSideProps? I need to fetch either http://localhost:3000/ or ...

Implementing JavaScript if statements that evaluate to true without cycling through all my if statements

Hey everyone, I've encountered an issue with my code. When testing each part individually, everything works fine. However, when all parts are combined and the first IF statement is reached, the form gets submitted without validating the others. Can an ...