[英]React.js fetch method on my api is not working?
我正在嘗試從托管在本地服務器上的數據庫執行簡單的提取請求,並且我在后端連接到 mongodb,我的提取方法似乎出了點問題。 我收到 Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR 和 Uncaught (in promise) TypeError: Failed to fetch
function App() {
const [state, setState]= useState({
track: '',
artist:'',
album:'',
year: 1990
}
)
// const [token, setToken] = useState('');
useEffect(() => {
async function getData(){
const track = await fetch('https://localhost:3001/api/music')
.then(res => res.json());
console.log(track)
setState(track)
// console.log(res)
}
getData();
},[])
also this is my route&controller functions
router.get('/', musicCtrl.index)
controller:
function index(req, res){
Music.find({}, function(err, music){
res.status(200).json(music)
})
}
mongo connection
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const musicSchema = new Schema({
track: String,
artist: String,
album: String,
year: Number
}, {timestamps:true});
module.exports = mongoose.model('Music', musicSchema);
請問有什么幫助嗎?!
您在提取 url 中使用 HTTPS。
改變
const track = await fetch('https://localhost:3001/api/music')
至
const track = await fetch('http://localhost:3001/api/music')
getData
function 也混合了await
和.then
。 將其更改為:-
async function getData(){
const track = await fetch('https://localhost:3001/api/music')
console.log(track.json())
setState(track.json())
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.