【发布时间】: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 它不是!
-
这是由
<form>提交触发的吗?您是否在阻止默认设置?
标签: javascript reactjs rest fetch-api