我正在尝试提供服务。凭证工作正常,因为我已经使用 thunderclient 对其进行了测试。但在实际应用程序中,每当我尝试通过添加或删除使用服务时,我都会在控制台中收到此错误。这些是我在控制台中遇到的添加和删除错误。
POST http://localhost:5000/api/notes/addnote 401 (Unauthorized) NoteState.js:27
DELETE http://localhost:5000/api/notes/deletenote/undefined 401 (Unauthorized) NoteState.js:43
我不知道是否需要实施任何安全更改来解决此问题。
NoteState.js
import NoteContext from "./noteContext";
import { useState } from "react";
const NoteState = (props) => {
const host = "http://localhost:5000"
const notesInitial = []
const [notes, setNotes] = useState(notesInitial)
// Get all Notes
const getNotes = async () => {
// API Call
const response = await fetch(`${host}/api/notes/fetchallnotes`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
"auth-token": localStorage.getItem('token')
}
});
const json = await response.json()
setNotes(json)
}
// Add a Note
const addNote = async (title, description, tag) => {
// TODO: API Call
// API Call
const response = await fetch(`${host}/api/notes/addnote`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
"auth-token": localStorage.getItem('token')
},
body: JSON.stringify({ title, description, tag })
});
const note = await response.json();
setNotes(notes.concat(note))
}
// Delete a Note
const deleteNote = async (id) => {
// API Call
const response = await fetch(`${host}/api/notes/deletenote/${id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
"auth-token": localStorage.getItem('token')
}
});
const json = response.json();
console.log(json);
const newNotes = notes.filter((note) => { return note._id !== id })
setNotes(newNotes)
}
// Edit a Note
const editNote = async (id, title, description, tag) => {
// API Call
const response = await fetch(`${host}/api/notes/updatenote/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
"auth-token": localStorage.getItem('token')
},
body: JSON.stringify({ title, description, tag })
});
const json = await response.json();
console.log(json);
let newNotes = JSON.parse(JSON.stringify(notes))
// Logic to edit in client
for (let index = 0; index < newNotes.length; index++) {
const element = newNotes[index];
if (element._id === id) {
newNotes[index].title = title;
newNotes[index].description = description;
newNotes[index].tag = tag;
break;
}
}
setNotes(newNotes);
}
return (
<NoteContext.Provider value={{ notes, addNote, deleteNote, editNote, getNotes }}>
{props.children}
</NoteContext.Provider>
)
}
export default NoteState;
中间件
获取用户.js
const jwt = require('jsonwebtoken');
const JWT_SECRET = 'Harryisagoodb$oy';
const fetchuser = (req, res, next) =>{
//GET the user from jwt token and add id to req object
const token = req.header('auth-token');
if(!token){
res.status(401).send({error: "Please authenticate using a valid token"})
}
try {
const data = jwt.verify(token, JWT_SECRET);
req.user = data.user;
next();
} catch (error) {
res.status(401).send({error: "Please authenticate using a valid token"})
}
}
module.exports = fetchuser;
任何帮助将不胜感激!!