如何避免 React fetch API 替换 url

How to avoid React fetch API replacing url

我已经用 React Fetch API 发出了 POST 请求,它按预期工作,除了它替换了当前页面的 url。

Post函数:

  postNote(note) {
    console.log('Posting note');

    fetch('http://localhost:9000/notes/create', {
      mode: 'cors',
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(note)
    })
  }

当这个函数执行时,它将我的 url 替换为:

http://localhost:3000/?name=nameExample&description=descExample

我不知道为什么会这样,因为我以前用过这个API,我没有遇到这个问题。如果有人能给我任何帮助,我将不胜感激。

提前致谢,祝您度过愉快的一周!

编辑 1:

我这样创建笔记对象:

const newNote = {id: 0, name: note.name, description: note.description, author_id: note.author_id, author: note.author };

编辑 2:

postNote功能由这个函数触发:

addNote = note => {
        const newNote = {id: 0, name: note.name, description: note.description, author_id: note.author_id, author: note.author };
        this.setState({
            notas: [...this.state.notas, newNote]
        });
        console.log(newNote);

        this.postNote(newNote);
    }

编辑 3:

<button className="btn btn-primary" onClick={() => {
      let newNote = { id: 0, name: this.name, description: this.description, author_id: this.author_id, author: this.author }
      noteContainer.addNote(newNote)
      }
 }>
      Save
</button>

<button>s 在 <form>s 内触发 submit 事件。如果您不阻止 submit 事件使用 event.preventDefault() 触发默认操作,表单将执行它的正常操作;将表单数据发布到您指定为 <form>action 的任何 URL。

由于您试图覆盖正常功能并以您自己的方式提交数据,请告诉 <form> 不要执行此正常操作。

document.getElementById("foo").addEventListener("submit", e => {
  e.preventDefault();

  // If the e.preventDefault() weren't there,
  // you would navigate to some.html on the Stack Snippets host
  // (it doens't exist so you actually get a 404 or something

  console.log("Hello");
});

document.getElementById("bar").addEventListener("click", e => {
  e.preventDefault();

  // Same thing here, except we prevent the click
  // event from triggering the submit event higher up

  console.log("World");
});
<form id="foo" action="some.html">
  <button>Click Me</button>
</form>

<form action="some.html">
  <button id="bar">Click Me 2</button>
</form>