Home > front end >  How do you send a request with data to an API in ReactJS that will then respond?
How do you send a request with data to an API in ReactJS that will then respond?

Time:11-30

I've been watching videos, reading tutorials, following steps by step and nothing seems to work. Right now, I have this as my code, but my API call is returning 404:

root / server.js

const express = require("express");

const PORT = process.env.PORT || 3001;

const app = express();

app.get("/api", (req, res) => {
  console.log(req);
  res.json({ message: "Hello from server!" });
});

app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});

root / client / app.js

import React from "react";
import "./App.css";
import $ from "jquery";

function App() {
  var [data, setData] = React.useState(null);

  const api = "http://localhost:3001/api";

  React.useEffect(() => {
    $.post(
      api,
      {
        username: "bobs",
        password: "pizza",
      },
      function (data, status) {
        setData = data;
        console.log(status   " "   data);
      }
    );
  }, []);

  return <>{!data ? "Loading..." : data}</>;
}

export default App;

As you can see, I'm trying to use jQuery to do an AJAX call to the server.

If (while the server is running - npm start) I go to http://localhost:3001/api, I get the following message displayed:

{"message":"Hello from server!"}

This is good - it's what it should say.

When I check my Developer tools (Chrome) > Network, I see the following:

enter image description here

enter image description here

enter image description here

My apologize if that's too much info - just trying to make sure I cover all my bases.

I also tried the following structures:

Stackoverflow - Handling ajax with React

AJAX and APIs - React

How to Create a React App with a Node Backend: The Complete Guide

How to Set up a Node.js Express Server for React

YouTube - Call API in React Js | How to send data from frontend to backend react

Each one provides me with some kind of error, from CORS, to 404.

Any suggestions would be greatly appreciated. If possible, I'd love to stick with jQuery/AJAX since I'm most familiar with it.

CodePudding user response:

the route method is get and you're sending a post request from react, this is how you r react code should look

import React from "react";
import "./App.css";
import $ from "jquery";

function App() {
  var [data, setData] = React.useState(null);

  const api = "http://localhost:3001/api";

  React.useEffect(() => {
    $.get( api,{
        username: "bobs",
        password: "pizza",
      },
      function (data, status) {
        setData = data;
        console.log(status   " "   data);
      });
  }, []);

  return <>{!data ? "Loading..." : data}</>;
}

export default App;
  • Related