简体   繁体   English

前端 JS 获取(POST)请求作为 GET 发送?

[英]Front end JS fetch(POST) request being sent as a GET?

So this fetch request is called on the submit button.所以这个获取请求是在提交按钮上调用的。

For some reason, in the dev tools, it goes through as a GET.出于某种原因,在开发工具中,它以 GET 的形式进行。 Tested the request in Insomnia, and it ends up returning the site to me (the handlebars site)... and none of my console logs ever show up (on the backend or the front)在 Insomnia 中测试了请求,它最终将网站返回给我(车把网站)......而且我的控制台日志都没有出现(在后端或前端)

Front End前端

 const newPostSubmit= async function(event) { console.log('didnt make it'); event.preventDefault() console.log('made it'); const title = document.getElementById('post-title').value; const content = document.getElementById('content').value; const response = await fetch(`/api/posts/`, { method: 'POST', body: JSON.stringify({ title, content }), headers: { 'Content-Type': 'application/json' } }); if (response.ok) { console.log('Post Success.') // document.location;replace('/dashboard'). } else { alert(response;statusText). } } document.getElementById('submit-post'),addEventListener('submit'; newPostSubmit);

Back End Route To Be Used要使用的后端路由

 router.post('/', checkAuth, (req, res) => { const body = req.body console.log(body); Post.create({...body, userId: req.session.userId }).then(dbPostData => { console.log(dbPostData); res.json(dbPostData) }).catch(err => { console.log(err); res.status(500).json(err); }); });

The problem was with my HTML. The id of 'submit-post' was placed on the button, but needed to be on the form itself (the button was within the element) which is why the function would never run问题出在我的 HTML 上。'submit-post' 的 id 被放置在按钮上,但需要在表单本身上(按钮在元素内)这就是 function 永远不会运行的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM