【发布时间】:2022-01-31 06:26:40
【问题描述】:
我也遇到这个错误
GET http://localhost:5000/api/notes/fetchallnotes
我的 noteState.js 文件中出现此错误,
import NoteContext from "./noteContext";
import { useState } from "react";
const NoteState = (props) => {
const host = "http://localhost:5000";
let initialNotes = []
const [notes, setNotes] = useState(initialNotes)
const authToken =localStorage.getItem('token');
const getNotes = async () => {
// API Call
const response = await fetch(`${host}/api/notes/fetchallnotes`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
"auth-token": authToken
}
});
const json = await response.json()
console.log(json);
setNotes(json)
}
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": authToken,
},
body: JSON.stringify({ title, description, tag })
});
console.log("Adding a note successfully")
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": authToken,
},
});
const json = await response.json();
console.log(json);
console.log("Note deleted successfully" + _id)
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: 'POST',
headers: {
'Content-Type': 'application/json',
"auth- token": authToken,
},
body: JSON.stringify({ title, description, tag })
});
const json = await response.json();
setNotes(json);
// Logic to edit in client
for (let index = 0; index < notes.length; index++) {
const element = notes[index];
if (element._id === id) {
element.title = title;
element.description = description;
element.tag = tag;
}
}
}
return (
<NoteContext.Provider value={{ notes, addNote, deleteNote, editNote, getNotes }}>
{props.children}
</NoteContext.Provider>
)
}
export default NoteState;
一旦我将 localstorage.getItem 更改为 localstorage.getitem,就会出现此特定错误,但随后我无法获取数据库中的笔记,我在登录组件中设置了 localstorage 项目,这是我的login.js 文件
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
const Login = (props) => {
const [credentials, setCredentials] = useState({ email: "", password: "" });
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch("http://localhost:5000/api/auth/login", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email: credentials.email, password: credentials.password })
});
const json = await response.json();
console.log(json);
if (json.success) {
// Save the auth token and redirect
localStorage.setItem('token', json.authtoken);
props.showAlert("Logged in successfully", "success")
navigate('/');
}
else {
props.showAlert("Please enter valid credentials", "danger")
}
}
const onChange = (e) => {
setCredentials({ ...credentials, [e.target.name]: e.target.value })
}
return (
<div>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input type="email" className="form-control" id="email" name='email' value={credentials.email} aria-describedby="emailHelp" onChange={onChange} placeholder="Enter email" />
</div>
<div className="form-group my-2">
<label htmlFor="Password">Password</label>
<input type="password" className="form-control" id="Password" name='password' value={credentials.password} onChange={onChange} placeholder="Password" />
</div>
<button type="submit" className="btn btn-primary my-2">Submit</button>
</form>
</div>
)
};
export default Login;
我已经在我的 Notes.js 文件中映射了我的笔记,我不知道为什么会出现这个错误,这是我的 Notes.js 文件
import React, { useContext, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom';
import noteContext from '../context/notes/noteContext';
import AddNote from './AddNote';
import Noteitem from './Noteitem';
export const Notes = (props) => {
let navigate = useNavigate();
const context = useContext(noteContext)
const { notes, getNotes } = context;
useEffect(() => {
if (localStorage.getItem('token')) {
getNotes();
}
else {
navigate('/login')
}
// eslint-disable-next-line
}, [])
const updateNote = (props) => {
ref.current.click()
}
const ref = useRef(null)
return (
<>
<AddNote showAlert={props.showAlert} />
<button type="button" ref={ref} className="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
{/* <!-- Modal --> */}
<div className="modal fade" id="exampleModal" tabIndex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-body">
...
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" className="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<div className="row my-3">
<h3 > Your Notes </h3>
<div className="container">
{notes.length === 0 && 'No notes to display'}
</div>
{notes.map((note) => {
return <Noteitem key={note._id} updateNote={updateNote} note={note} />
})}
</div>
</>
)
}
【问题讨论】:
标签: javascript reactjs fetch localhost