问题
Can anyone tell me how to integrate my Restful API in html page using JavaScript?
My API is working in postman and now I want to integrate them with HTML page. API is coded in PHP.
Need Help!
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Only fetch API</h2>
<script>
fetch('https://smweb.in/hungaroo/app/api/plan_list',{
method:'POST',
redirect: 'follow',
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
},
})
.then(function (response){
return response.text();
})
.then(function(data){
console.log(data);
})
</script>
</body>
</html>
Here is my code to display data from API but it's retrieve nothing. give error as failed to fetch
Please can anyone tell me how can I retrieve data form my API.
回答1:
Your CORS Settings are not working:
In your PHP
at the very beginning you should add:
// Allow access to your script from *, you can replace this with
// the Domain of your HTML File.
header("Access-Control-Allow-Origin: *");
// In Javascript, you request "Content-Type": "application/json",
// so you need to allow "Content-Type" on the Server side
header('Access-Control-Allow-Headers: Content-Type');
In JavaScript
add mode: 'cors',
and Remove "Access-Control-Allow-Origin": "*",
Off topic hint
And I would recomend switch <meta charset="ISO-8859-1">
to <meta charset="utf-8">
but that has no effect on your question.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2> only fetch APi</h2>
<script>
fetch('https://smweb.in/hungaroo/app/api/plan_list',{
method:'POST',
mode: 'cors',
redirect: 'follow',
headers: {
"Content-Type": "application/json"
},
})
.then(function (response){
console.log('Response:', response);
return response.text();
})
.then(function(data){
console.log('Success:', data);
})
.catch(function(error){
console.log('Error:', error)
})
</script>
</body>
</html>
You can press the Run
button and see the result.
Here you can find more settings for CORS: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode#Syntax
来源:https://stackoverflow.com/questions/59982383/implement-restful-api-using-javascript