【问题标题】:Form data not populating in API with POST request -Svelte使用 POST 请求 -Svelte 未在 API 中填充表单数据
【发布时间】: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


    【解决方案1】:

    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));
    };
    

    【讨论】:

    • 也移动,将options 构建到处理程序中,否则它将只有初始主体
    猜你喜欢
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多