Home > OS >  The server successfully processed the request but failed to return the data
The server successfully processed the request but failed to return the data

Time:11-16

The API executes on the insomnia Tool successfully, and responds successfully. However, On My Browser it does not respond with successful status, instead it shows status as 204 and (cancelled) also there is no error message on the console. The test data is also successfully added in the database despite the 204 & cancelled status. The server is running on the local host. The problem is that despite this, I am not receiving the intended response "statusCode": 200, "message": "User added Successfully"

Appreciate any assistance with this! Thank you!

enter image description here enter image description here

Client Side API call

         import axios from "axios";
            
                 let addUser = () => {
                        axios
                          .post(`http://localhost:3000/users/signup`, {
                            firstName: "testFirstName",
                            lastName: "testLastName",
                            email: "[email protected]",
                            password: "testPassword",
                          })
                          .then((res) => {
                            console.log(res);
                            console.log(res.data);**
                          })
                          .catch((e) => {
                            console.log(e);
                          });
                      };
return (
    <form>
    ... 
         <button type="submit" onClick={addUser}>submit</button>
    ...
    </form>
);

Server Side

const express = require("express");
const userRouter = express.Router();
const { User } = require("../../models");
const bcrypt = require("bcrypt");

userRouter.post("/signup", async (req, res) => {
  // get req body

  const { firstName, lastName, email, password } = req.body;

  //validate incoming request

  try {
    const user = User.build({
      firstName,
      lastName,
      email,
      password,
    });
    await user.validate();
  } catch (e) {
    res.status(400).json({
      statusCode: 400,
      message: "validation failed",
      details: e.errors[0].message,
    });

    return;
  }

  //encrypt the password with bcrypt

  const saltRounds = 10;
  try {
    let hash = await bcrypt.hash(password, saltRounds);

    // update database
    let user = await User.create({
      firstName,
      lastName,
      email,
      password: hash,
    });

    // respond to the request

    res.status(200).json({
      statusCode: 200,
      message: "User added Succcessfully",
      data: user,
    });
  } catch (e) {
    res.status(500).json({
      statusCode: 500,
      message: "Internal Server Error",
      details: e.errors[0].message,
    });
  }
});

enter image description here

In My (nodeJS) main Server Index.JS file I have enabled All CORS Requests

...

    const cors = require("cors");
    
    app.use(cors());
    
    app.use(express.json());
    
    app.listen(3000, async () => {
      console.log("http://localhost:3000/");
      try {
        await db.sequelize.sync({ alter: true });
      } catch (e) {
        console.log(`Database not connected due to error ${e}`);
      }
    });
    
    app.use("/users", userRouter); // Mount the router as middleware at path /user
    
    
    app.use((req, res) => {
      res.status(404).json({
        msg: " file not found",
      });
    });

...

CodePudding user response:

Try change your button markup into

 <button onClick={() => addUser()}>submit</button>

CodePudding user response:

Because it says cancelled, it is probably a cors issue. You can hover the mouse on "cancelled" and a tooltip will show up why.

You probably needed to configure cors a bit more.

app.use(cors(
  {
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    "Access-Control-Allow-Credentials": true
  }
));

CodePudding user response:

Resolved:

The reason is, the elements submits the form on the click event interrupting the API call. Hence the action causes a load to be interrupted. This can happen when a new navigation interrupts an existing one.

To prevent request from being cancelled, JavaScript event.preventDefault(); has to be called:

Please read the below article that helped me solve this, hope this helps you too!

https://newbedev.com/what-does-status-canceled-for-a-resource-mean-in-chrome-developer-tools

  • Related