Issue encountered while attempting to send a POST request from a React application to the Rocket backend

When attempting to send a POST request from my single page application, I encounter a 404 error, even though the route functions properly in Postman.

routes.rs

#[post("/letters", format = "application/json", data = "<new_letter>")]
fn write_letter(new_letter: Json<NewLetter>, conn: DbConn) -> Json<Value> {
    Json(json!({
        "status": Letter::write(new_letter.into_inner(), &conn),
        "result": null
    }))

}

I have configured my main.rs file to handle CORS

let (allowed_origins, failed_origins) = AllowedOrigins::some(&["http://localhost:3000"]);
let options = rocket_cors::Cors {
    allowed_origins: allowed_origins,
    allowed_methods: vec![Method::Get, Method::Put, Method::Post, Method::Delete]
        .into_iter()
        .map(From::from)
        .collect(),
    allowed_headers: AllowedHeaders::all(),
    allow_credentials: true,
    ..Default::default()
};

All routes function correctly in Postman, and GET requests work from the application. However, a 404 error is encountered when attempting a POST request from the application. The backend logs display the following error:

OPTIONS /api/letters:
=> Error: No matching routes for OPTIONS /api/letters.
=> Warning: Responding with 404 Not Found catcher.
=> CORS Fairing: Turned missing route OPTIONS /api/letters into an OPTIONS pre-flight request
=> Response succeeded.

Here is the relevant front end code:

writeLetter: (letter) => axios.post(`${base_url}/api/letters`, letter)
  .then(res => {
     if (res.status == 201) {
      console.log("letter successfully submitted")
      return res
    }
    throw new Error(res.error)
  }),

Is the issue with my Axios implementation or rocket_cors setup? I came across a similar issue but it seems like I have configured it correctly.

Answer №1

Initially, I was misled by the way the OPTIONS route was logging. Despite seeing a line that said

Warning: Responding with 404 Not Found catcher
, the following line indicated Response succeeded. This discrepancy prompted me to investigate further in DevTools.

Upon closer inspection, I discovered that the OPTIONS request was actually returning a 200 response. My oversight in only accounting for a 201 response led to an error.

To resolve this issue, I made a simple update to my API code:

if (res.status == 201 || res.status == 200) {
  console.log("letter successfully submitted")
  return res
}

With this modification, I successfully prevented the error from occurring.

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

Request from across origins in AmpersandJS is being made

Here is a sample AmpersandJS model: var AmpersandModel = require('ampersand-model'); module.exports = AmpersandModel.extend({ urlRoot: 'http://0.0.0.0:4567/api/v1/people', props: { id: 'any', name: [& ...

How can we refresh the model in Angular.js from a section of the application that has not been 'angularized' yet?

UPDATE: Found a similar question at Call Angular JS from legacy code Working on adding a new feature to an existing application using Angular. Unable to do a complete rewrite, so the challenge is integrating Angular models with the rest of the app that di ...

Tips for updating a React state while using the history API

In an effort to simplify and stay focused on the problem, I recently wrote a brief piece of code. Within this code, there is a component containing a Dialog that plays a role in a commercial process. This Dialog allows users to input information such as no ...

What is the best way to display HTML in this particular situation?

This is the function I am working on: public static monthDay(month: number): string { let day = new Date().getDay(); let year = new Date().getFullYear(); return day + ", " + year; } I am trying to add <span></span> tags around ...

The uiGmapGoogleMapApi.then function is failing to execute on Android devices

I successfully incorporated angular-google-maps into my Ionic project - in index.html, I included the following scripts: <script src="lib/lodash.min.js"></script> <script src="lib/angular-google-maps.min.js"></script> Within my vi ...

Ways to showcase an alert or popup when clicking?

I am utilizing a date picker component from this site and have enabled the 'disablePast' prop to gray out past dates preventing selection. Is there a way to trigger an alert or popup when attempting to click on disabled days (past dates)? Any sug ...

After the checkbox is clicked, I must send a boolean value to the function through the input flag in AngularJS

<input class="bx--toggle" id="toggle-view" type="checkbox" ng-model="vm.monthView" ng-change="vm.getRelevantData()" ng-attr-data-modal-target="{{vm.alertForSaveAll ? '#add-save-all-alert-modal': 'undefined'}}"> Within this p ...

Tips for ensuring the border matches the size of the image

I am in the process of creating a website that includes a filter option. My plan is to have the filters displayed on the left side and the items on the right side. To achieve this layout, I have implemented a scrollable div for the items. However, I notic ...

The Node.js promise failure can be unpredictable, despite being properly managed

In my journey to master MongoDB, I am currently exploring its capabilities by building a basic blog application. However, I have encountered an issue with the code responsible for saving blog posts - it seems to be inconsistent in its success rate, sometim ...

Getting the ajax response by utilizing a custom attribute within a php loop is definitely a handy trick

Currently working on integrating ajax with php. I have a set of buttons within a loop, and I am trying to display or fetch data (number) in the correct place/div using the "attr" method in jQuery. However, it seems that it is not functioning as expected on ...

Menu options disappearing upon clicking within the container area

Every time I click inside the dropdown menus, they unexpectedly close. This issue is persistent in both the Login menu and the nav bar. Although I’m not a seasoned web developer, I suspect it’s just a simple error that I’ve been overlooking all day ...

Performing a Protractor test on an Angular 5 application

We're in the process of transitioning our ui-library from AngularJS to Angular 5. I'm encountering challenges with the protractor tests. I need guidance on how to update the old AngularJS test to align it with Angular 5. If anyone has dealt wit ...

An easy guide to sorting outcomes using JSON

I have JSONResults in my Controller that contains all the data from a table. On the client's HTML detail view page, I am using JavaScript to fetch this data. How do I extract data from JSON where the client name is equal to klID (this is a JSON string ...

Obtain the contenteditable span's value

I'm facing an issue with a content editable span - I want to extract its value when the post button is clicked, but it's not working as expected. Please note that I am unable to convert the span to a textbox or div, I specifically need the value ...

Creating a duplicate object in a React component

I am currently developing a basic react application with inputs such as first name, last name, etc... The input states are managed using context api in the following context.js: import React, { useState } from "react"; export const FormContext ...

Why is the refresh endpoint generating new tokens when an outdated refresh token is used?

Greetings! I am currently utilizing two npm libraries, namely bcrypt and jsonwebtoken. I have implemented an endpoint called /refresh-token wherein I aim to generate a new set of access and refresh tokens. The process involves sending the refresh token to ...

In what way does JavaScript determine the timing for executing a function that is passed by reference implicitly? Illustrate with a

Within my React example application, I have assigned the function "manipulateUsername" as an event listener to a child component by passing it as a reference. Here is the code snippet from App.js: import React, { Component } from 'react'; impor ...

Untangling REGEX URLs for Effective Filtering

I am currently working on creating a filter for a video list. I have successfully put together a string that includes all the values selected by the user for filtering. Right now, I am passing this string as a parameter through the URL. For example: NOTE ...

Determine the character's position in an input field by tracking mouse movements

I am in need of a way to determine the position of a character in an input field based on mouse movement. For example, if the input field contains the value 'abcde' and I hover my mouse over the character 'a', the position should be ...

The PHP function is failing to communicate with jQuery and Ajax

Having trouble with PHP return to jQuery/Ajax functionality, When I try to edit an item, the error message displays even though the success function is executed. On the other hand, when attempting to delete an item, nothing is displayed despite the succes ...