localStorage函数不工作,得到一个set headers错误


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

这一行是发生可疑错误的地方。我已经阅读了收到这个错误的其他问题,我将在下面发布。我经常看到需要异步或等待的地方,但我错过了它

这是完整的错误。

(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((没有将任何头设置为"&";。它根本没有设置标题。

我读过这个问题:错误:Can';t在将标头发送到客户端后设置标头

我没有处于身体或完成状态,也没有在任何地方调用res.writeHead((。我可以将我的后端调用发布到/checkToken和/,如果这会有所帮助的话。

这是我的checkToken并获取/调用

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将尝试发送多个响应
  • 相关内容

    • 没有找到相关文章

    最新更新