简体   繁体   中英

How do i send a success status code to the front end using node.js?

I have recently started using node.js as my backend and I have successfully posted data to the database, the problem that I am facing now is telling the front end that data has been successfully saved. Below is my user route with all the things I have tried commented out.

import { Router } from 'express';
import { IUser } from '../models/user.model';
const User = require('../models/user.model');
// import bcrypt from 'bcrypt';

const bcrypt = require('bcrypt');
const bodyParser = require('body-parser');

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

const userRouter = Router();

userRouter.get('/', (req, res) => {
    return res.json('This is the user route');
})

userRouter.post("/register", (req, res: any, next) => {


    const user: IUser = new User({

        email: res.email,
        firstName: res.firstName,
        lastName: res.lastName,
        password: res.password,
        displayName: res.displayName,
        cellNumber: res.cellNumber,
    });

    user.save()
        .then((result: any) => {

            res.status(201).json({
                message: 'Successfully created a new user!',
                result: result
            });
            // res.sendCode(201);
            // console.log(res);
            // res.status(201).send("User has been successfully created");
            //return 'User has been successfully created';

            // return Object({ message: "User has been successfully created" });

            // return res.status(201).send({
            //     message: "User has been successfully created",
            //     statusCode: 201
            // })

            // return res;

        })
        .catch((err: any) => {
            res.status(500).json({
                error: err
            })
        })


    // bcrypt.hash(req.body.password, 10)
    //     .then((hash: string) => {

    //         const user = new User({

    //             email: req.body.email,
    //             firstName: req.body.firstName,
    //             lastName: req.body.lastName,
    //             password: hash,
    //             displayName: req.body.displayName,
    //             cellNumber: req.body.cellNumber,
    //         });

    //         user.save()
    //             .then((res: any) => {

    //                 res.status(201).json({
    //                     message: 'Successfully created a new user!',
    //                     result: res
    //                 });

    //             })
    //             .catch((err: any) => {
    //                 debugger;
    //                 res.status(500).json({
    //                     error: Error
    //                 })
    //             })
    //     })

})

export default userRouter;

which I then export to the server.ts file which is below

import express = require('express');
//import cors from 'cors';
const cors = require('cors');
const bodyParser = require('body-parser')
import { Router } from 'express';
import mongoose from "mongoose";
import "dotenv/config"

//routes
import userRouter from './routes/user.routes';

//Create a new express instance
const app: express.Application = express();

app.get('/', function (req, res) {

    res.send('Hello World');

});

// //get router
// var router = express.Router();

//Database
mongoose.connect(`${process.env.MONGO_URI}`,
    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
    })
    .then(() => {
        console.log("Connected to MongoDB")
    })
    .catch(() => {
        console.log("Connection to Database has failed")
    })


var corsOptions = {
    origin: '*',
    credentials: true,
    methods: '*'
};



const routes = Router();

export default routes;

app.use(routes);

app.use(bodyParser.urlencoded({ extended: false }));

app.use(cors(corsOptions));

app.use("/user", userRouter);



routes.use('/user', userRouter);
routes.use(cors(corsOptions));

//use cors middleware
// router.use(cors(options));

app.listen(3000, function () {

    console.log('App is listening on port 3000!');

})

What is strange is that when I set breakpoints and analyse the res file, i can see the data that I would have posted from the front end. But the front end gets the 500 status code instead of the 201 that I want to be sending, even though it passes right over that code. I have googled the keys of my keyboard for three days now. So I am at a loss now.

All The latest changes can be found in the GitLab repository below https://gitlab.com/ShanahJr/SuperiorBallers

You just need to make use of res variable provided by express . Example -

module.exports.updateData = async (req, res, next) => {
    try {
        const data = await Editor.edit(req.body.query);

        res.status(200).json({ "status": true, "result": 'Edit successful!' })

    } catch (error) {
        console.log(error)
        res.status(200).json({ "status": false, "result": "Request Failed!" })
    }
}

This statement - res.status(200).json({ "status": true, "result": 'Edit successful!' })

Nowadays, express also suggests using res.sendStatus(200) over res.status(200)

You can lookup for status codes here

Use res.status(201).send() , res.status().json usually gets blocked by http rules especially when you activate https

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM