简体   繁体   English

如何使用 node.js 向前端发送成功状态码?

[英]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.我最近开始使用 node.js 作为我的后端,并且我已成功将数据发布到数据库,我现在面临的问题是告诉前端数据已成功保存。 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然后我将其导出到下面的 server.ts 文件

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.奇怪的是,当我设置断点并分析 res 文件时,我可以看到我会从前端发布的数据。 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.但是前端得到的是 500 状态代码,而不是我想要发送的 201,即使它直接通过了该代码。 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最新的更改可以在https://gitlab.com/ShanahJr/SuperiorBallers下面的 GitLab 存储库中找到

You just need to make use of res variable provided by express .您只需要使用express提供的res变量。 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!' })此语句 - res.status(200).json({ "status": true, "result": 'Edit successful!' })

Nowadays, express also suggests using res.sendStatus(200) over res.status(200)如今,express 还建议使用res.sendStatus(200)而不是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使用res.status(201).send() , res.status().json通常会被 http 规则阻止,尤其是当您激活 https 时

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将带有值的变量发送到所有路由 node.js 的前端 - send a variable with a value to front end of all routes node.js 使用 Node.JS、EJS 和前端 JS 构建可重用代码的最佳方式? - Best way to structure reusable code using Node.JS, EJS, and front end JS? 如何使用node.js来运行react.js前端? - how do use node.js to run react.js front-end? 如何使用 Node.js 服务器将我的图像数据从前端保存到 Mongoose 数据库 - How can I save my image data from front end to Mongoose database using Node.js server 如何使用 Fetch 在前端显示通过 HTTP (Node.js) 发送的图像? - How to display an Image sent through HTTP (Node.js) in the Front End using Fetch? 无法从 React 前端向 Node.js 后端发送 POST 请求 - Can't send POST request from React front-end to Node.js back-end 从前端javascript向后端node.js发送POST请求 - Send POST request from front-end javascript to back-end node.js 在Node.js中使用Express成功后,如何发送JSON响应并重定向到某些html页面? - How to send a JSON response and redirect to some html page after success in Node.js using express? 如何使用node.js请求模块发送文件? - How do I send a file with node.js request module? 如何不断地将消息从 node.js 发送到我的前端 - How to constantly send message from a node js to my front end
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM