如何解决表单数据未通过 POST 请求填充到 API 中 -Svelte
我正在尝试向我的 svelte 应用程序中的 API 提交发布请求。我正在使用绑定运算符将表单数据绑定到字段,但是当我点击提交时,API 正在接收初始空字符串值。如何将输入到表单中的数据填充到 API 中?
*我可以在 Postman 中发出帖子请求,所以我认为 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>
解决方法
将 fetch
请求移至 submitHandler
const submitHandler = () => {
console.log(opp);
dispatch("add");
const options = {
method: "POST",body: JSON.stringify({ opp }),headers: {
"Content-Type": "application/json",},};
fetch(url,options)
.then((res) => res.json())
.then((res) => console.log(res));
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。