Json-server未正确存储字段。

huangapple go评论144阅读模式
英文:

Json-server not storing fields properly

问题

以下是您提供的代码的中文翻译:

我正在使用一些React代码并尝试使用json-server。我编写了这段代码来实现一些简单的逻辑,以创建带有标题的笔记并将其存储在数据库中。为了模拟REST API,我使用了json-server。但对我来说有些地方似乎不起作用。当我通过curl或httpie发布新的笔记时,它起作用。但当我在我的应用程序中使用下面的表单时,它添加了新的笔记,但笔记是空的(只有id),没有内容和标题。我漏掉了什么?

这是代码:

import { useState } from "react";

export default function () {
    const [title, setTitle] = useState('title');
    const [content, setContent] = useState('content here');
    const [errorMessage, setErrorMessage] = useState('');

    let handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        try {
            let res = await fetch("http://localhost:3001/notes", {
                method: "post",
                body: JSON.stringify({
                    title: title,
                    content: content,
                })
            })
            let resJson = await res.json();
            console.log(resJson);
            if (res.status == 201) {
                setTitle('')
                setContent('')
            } else {
                setErrorMessage(`something went wrong, ${res.status}`)
            }
        } catch(err) { 
            console.log(err);
        }
    }

    return (
        <form onSubmit={handleSubmit}>
            <div className="flex flex-col">
                <input 
                type="text" 
                value={title}
                onChange={e => setTitle(e.target.value)}
                className="border-2 border-gray"/>
                <textarea
                    className="border-2 border-gray"
                    value={content}
                    onChange={(event) => setContent(event.target.value)}
                    autoFocus rows={5} wrap="soft"/>
                <button type="submit">Add</button>
                {errorMessage && <p>{errorMessage}</p>}
            </div>
        </form>
    );
}

我像这样运行json-server:

json-server --watch db.json --port 3001

curl(http)命令可以正常工作:

http post localhost:3001/notes --raw '{ "title": "A", "content": "B" }'

或:

http post localhost:3001/notes title="test" content="test content"

因为当我显示所有笔记时,我可以看到发送的内容:

[
    {
        "content": "test content",
        "id": 11,
        "title": "test"
    },
    {
        "content": "B",
        "id": 15,
        "title": "A"
    }
]

但当我使用我的应用程序时,添加到数据库的仅仅是:

{
    "id": 16
}

这里漏掉了什么?

英文:

I am playing with some react code and trying out json-server.
I wrote this code to have some simple logic to create notes with titles and store it in db. To mimic rest api I used json-server. But something doesn't work for me. When I post a new note through curl or httpie it works. But when I use this form in my app below, it adds the new note but the note is empty (it has only id), without content and title. What am I missing here?

The code is:

import { useState } from &quot;react&quot;;

export default function () {
    const [title, setTitle] = useState(&#39;title&#39;);
    const [content, setContent] = useState(&#39;content here&#39;);
    const [errorMessage, setErrorMessage] = useState(&#39;&#39;);

    let handleSubmit = async (e: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {
        e.preventDefault();
        try {
            let res = await fetch(&quot;http://localhost:3001/notes&quot;, {
                method: &quot;post&quot;,
                body: JSON.stringify({
                    title: title,
                    content: content,
                })
            })
            let resJson = await res.json();
            console.log(resJson);
            if (res.status == 201) {
                setTitle(&#39;&#39;)
                setContent(&#39;&#39;)
            } else {
                setErrorMessage(`something went wrong, ${res.status}`)
            }
        } catch(err) { 
            console.log(err);
        }
    }

    return (
        &lt;form onSubmit={handleSubmit}&gt;
            &lt;div className=&quot;flex flex-col&quot;&gt;
                &lt;input 
                type=&quot;text&quot; 
                value={title}
                onChange={e =&gt; setTitle(e.target.value)}
                className=&quot;border-2 border-gray&quot;/&gt;
                &lt;textarea
                    className=&quot;border-2 border-gray&quot;
                    value={content}
                    onChange={(event) =&gt; setContent(event.target.value)}
                    autoFocus rows={5} wrap=&quot;soft&quot;/&gt;
                &lt;button type=&quot;submit&quot;&gt;Add&lt;/button&gt;
                {errorMessage &amp;&amp; &lt;p&gt;{errorMessage}&lt;/p&gt;}
            &lt;/div&gt;
        &lt;/form&gt;
    );
}

I run json-server like this:

json-server --watch db.json --port 3001

The curl (http) command works fine:

http post localhost:3001/notes --raw &#39;{ &quot;title&quot;: &quot;A&quot;, &quot;content&quot;: &quot;B&quot; }&#39;

Or:

http post localhost:3001/notes title=&quot;test&quot; content=&quot;test content&quot;

Because when I display all notes I can see the content sent there:

http localhost:3001/notes
[
    {
        &quot;content&quot;: &quot;test content&quot;,
        &quot;id&quot;: 11,
        &quot;title&quot;: &quot;test&quot;
    },
    {
        &quot;content&quot;: &quot;B&quot;,
        &quot;id&quot;: 15,
        &quot;title&quot;: &quot;A&quot;
    }
]

But when I use my app, all that is added to the db is:

{
    &quot;id&quot;: 16
}

What is missing here?

答案1

得分: 1

"Maybe you are missing the headers in your fetch request, which is necessary to specify the content type of the data you're sending. You need to set the Content-Type header to application/json for the server to correctly understand the request payload."

英文:

Maybe you are missing the headers in your fetch request, which is necessary to specify the content type of the data you're sending. You need to set the Content-Type header to application/json for the server to correctly understand the request payload.

let res = await fetch(&quot;http://localhost:3001/notes&quot;, {
    method: &quot;post&quot;,
    headers: {
        &#39;Content-Type&#39;: &#39;application/json&#39;,
    },
    body: JSON.stringify({
        title: title,
        content: content,
    })
})

huangapple
  • 本文由 发表于 2023年4月11日 04:54:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定