ChatGPT활용, 프롬프트에 아래 내용 입력
Using javascript fetch, write a function that sends a post request to this address and receives the response as an await
생성된 답변을 frontend index.html파일에 넣어주세요.
async function sendPostRequest() {
const url = 'https://example.com/api'; // Replace with the actual API endpoint
const data = {
key1: 'value1',
key2: 'value2',
};
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json', // Set the content type to JSON
// You can add other headers if needed
},
body: JSON.stringify(data), // Convert data to JSON string
};
try {
const response = await fetch(url, requestOptions);
if (!response.ok) {
// Handle error here if the response status is not OK (e.g., 404, 500)
throw new Error(`Request failed with status ${response.status}`);
}
const responseData = await response.json(); // Parse response JSON
// responseData now contains the JSON response from the server
console.log(responseData);
} catch (error) {
// Handle any errors that occurred during the fetch or parsing
console.error('Error:', error);
}
}
// Call the function to send the POST request
sendPostRequest();
ChatGPT생성 답변
<script> 사이 붙여넣기 </script>