简体   繁体   English

尝试使用javascript从api获取数据

[英]Trying to fetch data from an api using javascript

I'am trying to fetch data from a online MongoDb database using javascript and html. 我正在尝试使用javascript和html从在线MongoDb数据库中获取数据。 but it doesn't work properly. 但它不能正常工作。 Also using jquery library too 也使用jQuery库

<div>
    <input type="submit" value="GET DATA FROM API" id="getAPI">
    <div id="result" ></div>
    <div ><h2>Input Form</h2></div>
    <form id="postData" >
    </form>
</div>
<!-- javascript part -->
<script>
    document.getElementById('getAPI').addEventListener('click', getAPI);
    function getAPI() {
        fetch('http://localhost:3000/api/seller')
            .then((res) => { return res.json() })
            .then((data) => {
                let result = `<h2> Random User Info From Jsonplaceholder API</h2>`;
                data.forEach((seller) => {
                    const {id, name, email} = seller
                    result +=
                        `<div>
                                <h5> User ID: ${id} </h5>
                                <ul>
                                    <li> User Full Name : ${name}</li>
                                    <li> User Email : ${email} </li>
                                </ul>
                             </div>`;
                    document.getElementById('result').innerHTML = result;
                });
            })
    }
</script>

<script src="jquery-3.3.1.min.js" type="text/javascript"></script>

 fetch("https://jsonplaceholder.typicode.com/users") .then(res => { return res.json(); }) .then(data => { let result = `<h2> Random User Info From Jsonplaceholder API</h2>`; data.forEach(seller => { const { id, name, email } = seller; result += `<div> <h5> User ID: ${id} </h5> <ul> <li> User Full Name : ${name}</li> <li> User Email : ${email} </li> </ul> </div>`; document.getElementById("app").innerHTML = result; }); }); 
 <div id="app"></div> 

Your Front End works well. 您的前端效果很好。 I replaced the api url in your code and everything is fine. 我在您的代码中替换了api网址,一切正常。 It might be something on the Back End. 它可能在后端。 Did you check the status code that you get from the server? 您是否检查了从服务器获得的状态代码?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM