【问题标题】:Postman Error [err_http_headers_sent]: cannot set headers after they are sent to the client Using ReactJS & NodeJS邮递员错误 [err_http_headers_sent]:使用 ReactJS 和 NodeJS 将标头发送到客户端后无法设置标头
【发布时间】:2022-02-09 23:06:06
【问题描述】:

[err_http_headers_sent]: cannot set headers after they are sent to the client

我已经在这个问题上停留了两个星期,其他有关此问题的 Stack Overflow 帖子似乎并没有解决这个问题。希望有人可以帮助解决这个问题。我在后端使用 ReactJS 和 NodeJS “express”。在 Postman 中测试时出现此错误。有谁知道我做错了什么?

server.js 文件:

import express from 'express';
import { routes } from '../routes/index';
import { initializeDbConnection } from './db';
const PORT = process.env.PORT || 8080;
const app = express();
//This allows access the body of POST/PUT requests in our route handlers as req.body
app.use(express.json());
//Add all the routes to Express server exported from routes/index.js
routes.forEach(route => {
     app[route.method](route.path, route.handler);
});
// Connect to the database, then start the server.
// This prevents from having to create a new DB
// connection for every request
initializeDbConnection()
    .then(() => {
        app.listen(PORT, () => {
            console.log(`Server is listening on port ${PORT}`);
        });
    });  

signuproute.js 代码

import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { getDbConnection } from '../src/db';
export const signUpRoute = {
    path: '/api/signup',
    method: 'post',
    handler: async (req, res) => {
        const { email, password } = req.body;
        const db = getDbConnection('react-auth-db');
        const user = await db.collection('users').findOne({ email });
        if (user) {
            res.sendStatus(409);
        }
        const passwordHash = await bcrypt.hash(password, 10);
        //change once you figure out what info you want to store from users
        const startingInfo = {
            hairColor: '',
            favoriteFood: '',
            bio: '',
        };
        const result = await db.collection('users').insertOne({
            email,
            passwordHash,
            info: startingInfo,
            isVerified: false,
        });
        const { insertedId } = result;
        jwt.sign({
            id: insertedId,
            email,
            info: startingInfo,
            isVerified: false,
        },
        process.env.JWT_SECRET,
        {
            expiresIn: '2d',
        },
        (err, token) => {
            if (err) {
                return res.status(500).send(err);
            }
            res.status(200).send({ token });
        });
    }
}

【问题讨论】:

    标签: node.js reactjs postman


    【解决方案1】:

    您可以尝试在资源上添加回报

    return res.sendStatus(409);
    

    return res.status(200).send({ token });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 2020-05-26
      • 2018-09-19
      • 2023-01-19
      • 2020-09-22
      • 2021-08-26
      • 2021-02-26
      相关资源
      最近更新 更多