I have a simple API that works in my browser through the url:
我有一个简单的API,它可以通过URL在我的浏览器中工作:
https://XXX.execute-api.us-east-2.amazonaws.com/testing/calculator?x=test&y=testing
I get a 200 response there.
我在那里得到了200个回复。
The problem is when I try to take 2 inputs from an HTML page then pass them into the API to get the response and display the data on the html page I get an error saying: An error occured: Load failed
问题是,当我尝试从一个HTML页面获取2个输入,然后将它们传递到API以获得响应并在html页面上显示数据时,我得到一个错误消息:出现错误:加载失败
It could be something to do with CORS or something within my JavaScript. I am new to AWS and JS so I have been asking chatGPT for help along the way.
它可能与CORS有关,也可能与我的JavaScript中的某个东西有关。我是AWS和JS的新手,所以我一直在向chat GPT寻求帮助。
Below is my javascript:
下面是我的脚本:
document.addEventListener('DOMContentLoaded', function() {
const calculateButton = document.getElementById('calculate-button');
const resultDiv = document.getElementById('result');
calculateButton.addEventListener('click', function() {
// Retrieve the values of x and y from the input fields
const x = parseFloat(document.getElementById('x').value);
const y = parseFloat(document.getElementById('y').value);
// Check if x and y are valid numbers
if (isNaN(x) || isNaN(y)) {
resultDiv.textContent = 'Please enter valid numbers for x and y.';
return;
}
// Make a GET request to your Lambda function with x and y as query parameters
fetch(`https://XXXX.execute-api.us-east-2.amazonaws.com/testing/calculator?x=${x}&y=${y}`)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// Handle the response data as needed
resultDiv.textContent = `Result: ${data.result}`;
})
.catch(error => {
resultDiv.textContent = `An error occurred: ${error.message}`;
console.error(error);
});
});
});
Could someone help me out with this issue?
有人能帮我解决这个问题吗?
I also am attaching my CORS settings for API gateway
CORS SETTINGS
我还为API网关CORS设置附加了我的CORS设置
更多回答
优秀答案推荐
我是一名优秀的程序员,十分优秀!