[英]React.js fetch method on my api is not working?
I am trying to do a simple fetch request from a database hosted on a local server and also I am connected to mongodb in the backend, it seems like something is going wrong with my fetch method.我正在尝试从托管在本地服务器上的数据库执行简单的提取请求,并且我在后端连接到 mongodb,我的提取方法似乎出了点问题。 I am getting Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR and Uncaught (in promise) TypeError: Failed to fetch
我收到 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);
any help please?!请问有什么帮助吗?!
You are using HTTPS in the fetch url.您在提取 url 中使用 HTTPS。
Change改变
const track = await fetch('https://localhost:3001/api/music')
to至
const track = await fetch('http://localhost:3001/api/music')
The getData
function is also mixing await
and .then
. getData
function 也混合了await
和.then
。 Change it to:-将其更改为:-
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.