localStorage 函数不工作,出现设置 headers 错误

localStorage functions not working, getting a set headers error

localStorage.setItem('auth-token', '');

这一行是疑似错误发生的地方。我已经阅读了收到此错误的其他问题,我将在下面 post。我经常在需要 async 或 await 的地方看到它,但我错过了它。

这是完整的错误。

(node:2211) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:547:11)
    at ServerResponse.header (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/response.js:267:15)
    at checkToken (/Users/devintripp/Desktop/unt-library-system/server/controllers/user-ctrl.js:132:32)
    at Layer.handle [as handle_request] (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/router/layer.js:95:5)
    at /Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/router/index.js:174:3)
    at router (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/router/index.js:47:12)
    at Layer.handle [as handle_request] (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/devintripp/Desktop/unt-library-system/server/node_modules/express/lib/router/index.js:317:13)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2211) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:2211) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我已经把它归结为这段代码。

import React, { useState, useEffect } from 'react';
import { BrowserRouter , Route, Switch } from 'react-router-dom';
import Axios from 'axios';

import { NavBar } from './components';
import SignIn  from './components/auth/SignIn';
import Register from './components/auth/Register';
import { BooksList, BooksInsert, BooksUpdate } from './pages';
import  UserContext  from './context/UserContext'

import 'bootstrap/dist/css/bootstrap.min.css'

function App() {

    //global state for the app to use
    const [userData, setUserData] = useState({
        token: undefined,
        user: undefined
    })


    useEffect( () => {
        const checkLoggedIn = async () => {
            let token = localStorage.getItem('auth-token');
            
            console.log(token); // this prints "" to the console in the browser
            localStorage.setItem('auth-token', ''); //this code never changes the headers in chrome

            if(token === null || token === ""){
                localStorage.setItem('auth-token', '');
                token = "";
            }

            const tokenResponse = await Axios.post("http://localhost:8174/user/checkToken", null,  {headers: {"x-auth-token": token}});
            if(tokenResponse.data){
                const userRes = await Axios.get("http://localhost:8174/user/", {headers: {"x-auth-token": token}})
                setUserData({token, user: userRes.data})
            }

        }



        checkLoggedIn();
    }, []);

return (
<div></div>
);


}

还需要注意的是 localStorage.setItem() 没有将任何 headers 设置为“”。它根本没有设置 headers。

我看过这个问题: Error: Can't set headers after they are sent to the client

我没有处于 body 或完成状态,也没有在任何地方调用 res.writeHead()。我可以 post 我的后端调用 /checkToken 和/如果这有帮助的话。

这是我的 checkToken 和 get / calls

checkToken = async (req, res) => {
    try {
        const token = req.header("x-auth-token")
        if(!token){
            res.json(false);
        }


        const verified = jwt.verify(token, process.env.JWT_SECRET);
        if(!verified){
            return res.json(false);
        }


        const user = await User.findById(verified.id);
        if(!user){
            return res.json(false)
        }

        return res.json(true)
    } catch (err) {
        return res.status(500).json({msg: err.message});
    }
}

getUser = async (req, res) => {
    const user = await User.findById(req.user);
    // console.log(user)
    if(!user){
        console.log("no user found")
        res.json({msg: "user not found"})
    }
    res.json({
        name: user.name,
        id: user._id
    })
}

这里是调用它们的地方。

const express = require("express");
// const userCtrl = require("../controllers/user-ctrl");
const router = express.Router();
const UserCtrl = require("../controllers/user-ctrl");
const auth = require("../middleware/auth");





router.post('/register', UserCtrl.registerUser);
router.post('/login', UserCtrl.loginUser);
router.delete('/delete', auth, UserCtrl.deleteUser);
router.post('/checkToken', UserCtrl.checkToken);
router.get('/', auth, UserCtrl.getUser);


module.exports = router;

最后是我的中间件

const jwt = require('jsonwebtoken');


const auth = (req, res, next) => {

    try{
        const token = req.header("x-auth-token")
        if(!token){
            return res.status(401).json({msg: "No authentication token found, auth denied."})
        }

        
        const verified = jwt.verify(token, process.env.JWT_SECRET);
     
        if(!verified){
            return res.status(401).json({msg: "Token verification failed, auth denied."})
        }

        req.user = verified.id
        // res.end();
        next();
    } catch (err) {
        res.status(500).json({error: err.message});
    }

}


module.exports = auth;

下面的答案回答了错误。我没有回复我发出的回复,所以它发送了多个回复并且像没有休息一样失败了;在案例结束时。

localStorage 然而仍然是一个问题,无法在 chrome 中设置。

这与评论和关闭请求中提到的问题相同。

问题

您尝试对同一个请求发送多个响应。尝试向同一请求发送多个响应是导致 Express 错误的原因。

这发生在您的 getUser 代码以及您的 checkToken 代码中。

    如果条件 !user 为真(如果 user 计算结果为 false),
  • getUser 尝试发送多个响应。
  • 如果 !token!verified!user 之一为真,
  • checkToken 将尝试发送多个响应。