Postman 错误 [err_http_headers_sent]:使用 ReactJS 和 NodeJS 将标头发送到客户端后无法设置标头



[err_http_headers_sent]:在将标头发送到客户端后无法设置标头<(链接为实际错误的图片(

我已经在这个问题上呆了两周了,其他关于这个问题的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 });
});
}
}

您可以尝试在res 上添加回报

return res.sendStatus(409);

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

最新更新