如何修正HTML中callAPIRead函数,实现REST GET API正常返回结果?
修复GET API调用问题的解决方案
问题分析与修复点:
- 函数名大小写不匹配:按钮的
onclick事件里写的是callAPIread(),但函数定义是callAPIRead(首字母R大写),导致点击按钮无法触发正确的函数,需统一函数名大小写。 - 响应解析逻辑错误:你的GET API直接返回字符串
Hello from Lambda Read,而非包含body字段的JSON对象,原代码中JSON.parse(result).body会触发解析错误,直接使用result即可获取返回内容。 - 可选优化:GET请求无需设置
Content-Type请求头,可移除该配置以简化代码。
修正后的完整代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World</title> <!-- Add some CSS to change client UI --> <style> body { background-color: #232F3E; } label, button { color: #FF9900; font-family: Arial, Helvetica, sans-serif; font-size: 20px; margin-left: 40px; } input { color: #232F3E; font-family: Arial, Helvetica, sans-serif; font-size: 20px; margin-left: 20px; } </style> <script> // define the callAPI function that takes a first name and last name as parameters var callAPI = (firstName,lastName)=>{ // instantiate a headers object var myHeaders = new Headers(); // add content type header to object myHeaders.append("Content-Type", "application/json"); // using built in JSON utility package turn object to string and store in a variable var raw = JSON.stringify({"firstName":firstName,"lastName":lastName}); // create a JSON object with parameters for API call and store in a variable var requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow' }; // make API call with parameters and use promises to get response fetch("**MY API POST URL**", requestOptions) .then(response => response.text()) .then(result => alert(JSON.parse(result).body)) .catch(error => console.log('error', error)); } var callAPIRead =()=>{ // create a JSON object with parameters for API call and store in a variable var requestOptions = { method: 'GET', redirect: 'follow' }; // make API call with parameters and use promises to get response fetch("**MY API GET URL**", requestOptions) .then(response => response.text()) .then(result => alert(result)) .catch(error => console.log('error', error)); } </script> </head> <body> <form> <label>First Name Input :</label> <input type="text" id="fName"> <label>Last Name Input :</label> <input type="text" id="lName"> <!-- set button onClick method to call function we defined passing input values as parameters --> <button type="button" onclick="callAPI(document.getElementById('fName').value,document.getElementById('lName').value)">Call API write</button> </form> <form> <!-- set button onClick method to call function we defined passing input values as parameters --> <button type="button" onclick="callAPIRead()">Call API read</button> </form> </body> </html>
内容的提问来源于stack exchange,提问作者Federico
相关产品推荐
相关产品推荐

