React Js: Promise rejection due to SyntaxError:

I've been attempting to make a POST request using the fetch method in reactjs. Despite going through some documentation, I haven't been able to resolve my error. Can someone please lend a hand?

Below is the snippet of my reactjs code:

 handleSubmit(e) {
       e.preventDefault();
       var self = this;
    
       const payload = {
       id: 111,
       studentName: 'param',
       age: 24,
       emailId: 2
    };
    fetch({
       method: 'POST',
       url: 'http://localhost:8083/students',
       body: payload,
       headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
     })
       .then(function(response) {
           return response.json()
         }).then(function(body) {
           console.log(body);
         });
     }
    
  }

If there's anyone familiar with reactjs, could you provide a straightforward example on how to execute a post request? It can be done using either fetch or axios.

Answer №1

Here is a quick demonstration.

fetch('https://exampleAPI.com/login',{
    method:'POST',
    headers:{
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body:JSON.stringify({
    email: userEmailAddress,
    password: userPassword
  })
  }).then(function (response) {

    //Check if response status is 200(OK) 
    if(response.ok) {
      alert("Welcome, you are logged in.");
    }
    //if not, throw an error to be caught in the catch block
    throw new Error(response);
  })
  .catch(function (error) {
    //Handle any errors
    console.log(error);
  });

For more detailed information on how to utilize the `fetch` function, visit https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Answer №2

I just addressed a similar query earlier. You can find the answer here.

The beauty of React lies in its simplicity - it's essentially Javascript.

So, all you really need is a method to perform a POST to your server!

You have the option to utilize the built-in fetch function or go for a more comprehensive library like axios

Here are examples using both approaches:

// ES7 async/await
const post_data = { firstname: 'blabla', etc....};
const res = await fetch('localhost:3000/post_url', { method: 'POST', body: post_data });
const json = await res.json();

// Using standard promises
const post_data = { firstname: 'blabla', etc....};
fetch('localhost:3000/post_url', { method: 'POST', body: post_data })
.then(function (res) { return res.json(); })
.then(function (json) { console.log(json); };

// AXIOS example directly from their Github
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(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

Tips for displaying a nested list in React.js

I am currently working with three arrays named persons, skills, and personSkills. My goal is to display all the skills associated with each person in an unordered vertical list just like this: Person1 - Skill1 - Skill2 Person2 - Skill3 - Skill4 T ...

How come I am receiving {"readyState":1} in the DOM instead of JSON data in AngularJS?

Currently, I am facing an issue where instead of the JSON data (which consists of only 49 items) showing up on the DOM, I am getting {"readyState":1}. I believe this is just a test to ensure that my code is functioning correctly. Although I have identifie ...

Uploading Images Dynamically with AJAX

Can someone assist me with a multiple upload form that utilizes AJAX to upload and display an image without the need for a submit button? My issue arises when dealing with repeating forms within table rows, causing only the first form to function properly. ...

Navigating Tabs and jQuery for JSON Data Refresh: A Step-by-Step Guide

Struggling to implement a basic UI and seeking advice from the community. Here's my current setup: 1) Using getJSON to fetch a JSON string (multidimensional array) from a PHP page. 2) Utilizing 2 jQuery.each loops to iterate through the JSON data and ...

Differences seen in display when using Internet Explorer's prependTo feature

Here is some code that I am working with:- <ul id="list1"> <li class="a">item 1</li> <li class="a">item 2</li> <li class="b">item 3</li> <li class="b">item 4</li> </ul> Additiona ...

Executing a console.log statement within an array nested inside a function of an object

Today in school, I learned about objects and how a function inside an object is actually called a method. In my method, I have an array and I'm trying to change a global variable to display a different location in the console.log. However, all I keep ...

Why does Javascript execute in this specific order?

I'm puzzled as to why JavaScript behaves in a certain way, or if I made an error in my code. How is it that the code after $.getJSON runs before the callback completes? window.ratingCallback = function(data){ if(data[0].code == 3){ ratin ...

Secure your Express.js session cookies for enhanced protection

Struggling to figure out how to set a secure cookie in the expressjs framework. Any suggestions on where I can find an option for this? ...

developing a plain old Java object that includes select elements from the response

Having trouble extracting data from a JSON response using a POJO. The response contains multiple attributes, but I only require a few. I have created the POJO with only those specific attributes, however, I encounter parsing errors while trying to read it. ...

Update JSON records based on specified conditions

Currently, I have a table that includes both an ID column and a JSON column. The ID column automatically increments with each new entry. Here is a sample of my data: First Row: 1 | { "HeaderInfo": { "Name": "ABC", ...

Heroku deployment failed: Push rejected due to lack of a Cedar-supported application

Trying to deploy my 3D game (created with three.js) on a Heroku server has brought up an issue. After running the command "git push heroku master," I encountered the following problem: Initializing repository, done. Counting objects: 252, done. Delta com ...

Managing Jawbone API OAuth access tokens using node.js (express and passport)

Is there anyone who has successfully completed the Jawbone's OAuth2.0 authentication process for their REST API? I am facing difficulty in understanding how to access and send the authorization_code in order to obtain the access_token as mentioned in ...

iOS fixed positioning and scrolling

One of the current challenges we are facing involves implementing an action button similar to the one found in GMail for adding new content. This button needs to remain fixed during scroll. Here is the HTML code: <div class="addButton actionButton" on ...

Passing dynamic props to Vue mixin: a guide

Can we pass dynamic props to a Vue mixin from its parent component? Here's the scenario. This mixin is set up to receive an isActive prop. mixin.ts export default { props: { isActive: { type: Boolean, required: true } }, wa ...

Switch the status of an individual item within a datalist using jQuery in an ASP.NET application

Currently, I have a database with Titles that are displayed using a datalist, where the content is initially hidden. The objective is to reveal the hidden content when each item is clicked, achieved through jQuery implementation. Below is the code snippet ...

Detect keypress within a BrowserWindow even when multiple BrowserView components are present

In my Electron application, I have a main BrowserWindow that contains the main user interface index.html, along with multiple BrowserView elements: browserWindow = new BrowserWindow({ width: width, height: height, frame: false }); browserWindow.webContents ...

Ways to delete a CSS attribute with jquery

Is there a way to eliminate a CSS property from a class without setting it to null? Let's say I have a class called myclass with the property right:0px. I want to completely remove right:0px from my class, not just set it to null. How can I achieve th ...

Ways to refresh the DOM while making an asynchronous request

Consider the following async function: async function predict_from_model() { $("#loading").html("first update") const model = await tf.loadModel('model.json'); $("#loading").html("second update") //delayed for (var i = 0; i < 100; i++ ...

Is the unit-converts npm package compatible with the website https://unpkg.com?

Having issues importing the npm package 'convert-units' using unpkg, I attempted the following method: <script src="unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="02616d6c746770762f776c6b767142302c31 ...

Using PHP to pass variables to an external JavaScript file

I have come across the following code snippet: PHP <?php include("db.php"); ?> <html> <head> <title>Title</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/j ...