我正在尝试编写代码,以便可以使用fetch api通过网站更改api数据-以下是代码
const url = 'https://oafc.herokuapp.com/api/players';
const nameDropdown = document.getElementById('nameDropdown');
const nameInput = document.getElementById('name');
const assistsInput = document.getElementById('assists');
const goalsInput = document.getElementById('goals');
const editPlayerSubmit = document.getElementById('editPlayerSubmit');
//Fill select with players fill inputs
function getPlayers(){
fetch(url)
.then((res) => res.json())
.then((data) => {
//Fill Select
for(i = 0; i< data.length; i++){
createOption(data[i].name , i);
};
function createOption(val , num){
let elem = document.createElement("option");
elem.innerHTML = val;
elem.value = num;
nameDropdown.appendChild(elem);
}
})
}
//Change inputs on name change
nameDropdown.addEventListener('change', () => {
fetch('https://oafc.herokuapp.com/api/players')
.then((res) => res.json())
.then((data) => {
let selected = nameDropdown.value;
let goals = data[selected].goals;
let name = data[selected].name;
let assists = data[selected].assists;
let id = data[selected]._id;
console.log(id);
goalsInput.value = goals;
nameInput.value = name;
assistsInput.value = assists;
})
});
getPlayers();
//When edit player submit btn is pressed
editPlayerSubmit.addEventListener('click', () => {
fetch(url)
.then((res) => res.json())
.then((data) => {
urlWithId = `https://oafc.herokuapp.com/api/players/${data[nameDropdown.value]._id}`;
let bodyData = {
name: nameInput.value,
goals: goalsInput.value,
asists: assistsInput.value
};
fetch(urlWithId, {
method: 'PUT',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(bodyData)
})
.then(response => response.json());
})
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Site Title</title>
<!-- Stylesheets -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="editPlayer">
<h1>Edit Player</h1>
<select id="nameDropdown"></select>
<br>
Name: <input type="text" id="name">
<br>
Goals: <input type="number" id="goals">
<br>
Assists: <input type="number" id="assists">
<br>
<button id="editPlayerSubmit">Submit</button>
</div>
<!-- Scripts -->
<script src="js/script.js"></script>
</body>
</html>
我自己开发了API,PUT请求通过postman工作,所以我知道我的CORS设置都是正确的。GET请求正在工作,所以我认为我可能在我编写的代码中搞砸了,这就是它不工作的原因
发布于 2018-05-31 18:22:42
我得到了
Failed to load https://oafc.herokuapp.com/api/players/5b0f171cacc1580004d5c07c: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
当我运行你的代码片段时。
看看这个answer来配置你的heroku应用。
https://stackoverflow.com/questions/50621946
复制相似问题