【问题标题】:How to avoid React fetch API replacing url如何避免 React fetch API 替换 url
【发布时间】:2019-06-28 12:33:56
【问题描述】:

我已经使用 react Fetch API 发出了一个 POST 请求,它可以正常工作,除了它替换了当前页面的 url。

发布功能:

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

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

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>

【问题讨论】:

  • package.json 中有代理吗?
  • 我不明白这怎么可能。 URL 是硬编码的,还是从某种变量中填充的。我会 console.log 该变量,并确保它用于端口 9000。
  • 您需要展示更多涉及的代码。 fetch 本身不会导致当前页面的 URL 发生变化。抓取是如何触发的?
  • 不,@stever 它不是!
  • 这是由&lt;form&gt; 提交触发的吗?您是否在阻止默认设置?

标签: javascript reactjs rest fetch-api


【解决方案1】:

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

由于您试图覆盖正常功能并以自己的方式提交数据,请告诉&lt;form&gt; 不要这样做是正常的操作。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 2021-06-03
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多