【发布时间】:2020-12-27 23:17:16
【问题描述】:
我正在尝试向我的苗条应用程序中的 API 提交发布请求。我正在使用绑定运算符将表单数据绑定到字段,但是当我点击提交时,API 正在接收初始的空字符串值。如何将输入到表单中的数据填充到 API 中?
*我可以在 Postman 中发出 post 请求,所以我认为 API 没有任何问题
这是我的表单组件:
<script>
import { createEventDispatcher} from 'svelte'
import Button from '../shared/Button.svelte'
let dispatch = createEventDispatcher()
let opp = {title: '', opp_type: '', opp_description: '', more_info: ''}
const url = 'https://bchangeapi.herokuapp.com/opps';
// request options
const options = {
method: 'POST',
body: JSON.stringify({opp}),
headers: {
'Content-Type': 'application/json'
}
}
// send POST request
fetch(url, options)
.then(res => res.json())
.then(res => console.log(res));
const submitHandler = () => {
console.log(opp)
dispatch('add')
}
</script>
<form on:submit|preventDefault={submitHandler}>
<div class="form-field">
<label for="title"> Title:</label>
<input type="text" id="title" bind:value={opp.title}>
</div>
<div class="form-field">
<label for="opp_type"> Opportunity Type:</label>
<input type="text" id="opp_type" bind:value={opp.opp_type}>
</div>
<div class="form-field">
<label for="opp_description"> Opportunity Description:</label>
<input type="text" id="opp_description" bind:value={opp.opp_description}>
</div>
<div class="form-field">
<label for="more_info"> More Info:</label>
<input type="text" id="more_info" bind:value={opp.more_info}>
</div>
<Button type='secondary' flat={true}>Add Opportunity</Button>
</form>
【问题讨论】:
标签: forms api post bind svelte