POST form data via rest - javascript

I have this endpoint:
#PostMapping("/createUser")
public ResponseEntity<User> createUser(#RequestBody User user) {...}
I have an HTML page where I want to create a user.
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label>
<input type="text" id="password" name="password"><br>
<button>Submit</button>
</form>
What is a good and simple way to post this request?

I would recommend using async / await
Add this to your button <button onclick="send()">Submit</button>
when it's clicked then call a function like send() here an example
async function send() {}
and inside the function you can use the below code snippet to send the data to your endpoint
async function send() {
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
const data = {username, password};
const options = {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data)
};
await fetch('/createUser', options);
}

I still don't understand what you want to do, but if you want to post that form, then you can add a Attribute to the <form> tag. Just do <form method="POST"> and then use Back-end to listen the POST.

Related

Second Post request puts form before URL for some reason

I'm creating a form using TailwindCSS and DaisyUI, which looks like this (removed the classes since they aren't relevant to this question):
<form id="form" >
<div>
<label for="name">Name</label>
<input id="name" type="text" name="name" required />
</div>
<div>
<label for="email">E-Mail</label>
<input id="email" type="email" name="email" required />
</div>
<div>
<label for="text">Info</label>
<textarea id="text" name="text" rows="5"></textarea>
</div>
<div>
<button id="submit-button" type="button">Request</button>
</div>
</form>
Since I plan to display some message after the request, I changed the button type to "button" and created this script using JQuery:
async function sendRequest(data) {
let response = await fetch('api/anfrage', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
"cache-control": "no-cache"
},
body: JSON.stringify(data)
})
let content = await response.json()
console.log(content)
return false
}
$(document).ready(() => {
$('#submit-button').click(() => {
let data = {
name: $('#name').val(),
email: $('#email').val(),
text: $('#text').val()
}
console.log(data)
sendRequest(data)
})
})
My backend is a Flask server, which has this endpoint:
#index_bp.route("/api/anfrage", methods=["POST"])
def request_meeting():
print("request_meeting")
return {"yes": "yesss"}
Everything works exactly as you would suspect on the first run. However, when I submit the same form again, I'm getting this error from my Flask server:
"{"name":"dasdf","email":"galstyan.artu#gmail.com","text":"asdf"}POST /api/anfrage HTTP/1.1" 405 -
For some reason, the content of my form is placed before the POST request. It's incredibly confusing and I've never had this before. If I don't send a second request and instead refresh the page, I'm getting this error:
127.0.0.1 - - [04/Sep/2022 13:12:31] "{"name":"dasdf","email":"galstyan.artu#gmail.com","text":"asdf"}GET / HTTP/1.1" 405 -
Does anyone have an idea? Thanks :)

Form submit value giving null - mongoose and express js

I am trying to make a way to send data from a basic html form to mongodb using express. but it's giving me null when I post it.
I used the following Schema : commentname: String.
Here's the HTML:
<form id="form" onsubmit="return false;">
<input type="textbox" id="cmt-1" placeholder="comment here"/>
</form>
<button type="button" onclick="submit()" class="submit">
submit
</button>
JS:
var cmt = document.getElementById('cmt-1').value;
var comment = {commentname: ''};
comment = {commentname: cmt};
function submit () {
async function postData (url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
mode: 'same-origin',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData(
'https://realtime-comt-system-100.glitch.me/comments/add',{comment}
)
.then(data => { console.log(data); });
}
What am I missing?
just try this code but check the url i put . don't put the whole url just put the path name .
also take this code copy and paste , the html and the java script take them both because i changed both of them
var form = document.getElementById('form');
form.addEventListener('submit', async(e) => {
e.preventDefault();
let cmt = form.cmt.value;
let data = {commentname: cmt};
const response = await fetch('/comments/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(res =>{
console.log(res)
}).catch(err){
console.error(err)
}
})
<form id="form">
<input type="textbox" id="cmt-1" name='cmt' placeholder="comment here"/>
</form>
<button type="submit" onclick="submit()" class="submit">
submit
</button>
The problem is not being caused by the code posted above.
It's a Mongoose problem. You are trying to create two documents with the same id, when that id has been specified unique to Mongoose.
This is what the code is posting in the body to the backend, a JSON string:
{"comment":{"commentname":"my sample comment"}}
The fact that you're posting an object inside an object looks suspicious. This pattern would be more common:
{"commentname":"my sample comment"}
But since there is no backend code posted, it's impossible to tell if this is correct.
When I tried posting {"comment":{"commentname":"my sample comment"}} to the backend URL using Postman, I received the following response code:
400 Bad Request
The response body:
"Error: MongoError: E11000 duplicate key error collection: database.comments index: commentname_1 dup key: { commentname: null }"
From Mastering JS - Debug E11000 Errors in Mongoose
MongoDB's E11000 error is a common source of confusion. This error occurs when two documents have the same value for a field that's defined as unique in your Mongoose schema.
Mongoose models have an _id field that's always unique.

Improperly sending form data in html

So i would like to send Whatever i type in my input bar in to be sent to whatever api link via post method. But whenever i send it i get {} . The problem is when i dont send anything in the input bar A.K.A left blank and press submit i still get {}. But when i type gibberish its still {} . So i assume whatever i typed in is not being sent to the api link.
Also when i hard code something like body: JSON.stringify(this.myForm) it shows up as a response in the back end. So i believe i error lies withing this body of my fetch request. heres my code what should i put for the body.
<html>
<body>
<h1>Draft V0.1</h1>
<form class="form" id="myForm">
<label for="skill">add skill</label>
<input type="text" name="skill" id="skill">
<button type="submit">Submit</button>
</form>
<script>
const myForm = document.getElementById('myForm')
myForm.addEventListener('submit', function (e) {
e.preventDefault();
const formData = new FormData(this);
fetch('https://fj5s3i60a8.execute-api.us-east-1.amazonaws.com/updateSkill', {
method: 'post',
body: JSON.stringify(new FormData(myForm)),
headers:
{
"Content-Type": "application/json; charset=utf-8",
"Accept": 'application/json'
}
}).then(function (response) {
console.log(response)
return response.json();
});
});
</script>
</body>
</html>
Note I was blindly playing around with the body to see what i can parse through it but i would end up getting cors errors.
Thank you in advance
const thisForm = document.getElementById('myForm');
thisForm.addEventListener('submit', async function (e) {
e.preventDefault();
const formData = new FormData(thisForm).entries()
const response = await fetch('https://reqres.in/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.fromEntries(formData))
});
const result = await response.json();
console.log(result)
});
<html>
<body>
<h1>Draft V0.1</h1>
<form class="form" id="myForm">
<label for="skill">add skill</label>
<input type="text" name="skill" id="skill">
<button type="submit">Submit</button>
</form>
</body>
</html>

POST convert to GET when I want to fetch formData?

I want to send an image to server
my code works perfect in Chrome Version 77.0.3865.90
BUT
in Mozilla Firefox (version 69.0.1) POST method changes to GET with this error
Form contains a file input, but is missing method=POST and enctype=multipart/form-data on the form. The file will not be sent.
Request URL: http://localhost:3000/...
Request method: GET
Status code: 200
<form class="form-horizontal" id="form" >
<div class="col">
<label for="images" class="control-label">image</label>
<input type="file" class="form-control" name="images" id="images" >
</div>
<div class="form-group row">
<div class="col">
<button type="submit" class="btn btn-danger">Send</button>
</div>
</div>
</form>
<script>
document.getElementById('form').addEventListener('submit' , async function(event) {
let images = document.querySelector('input[name="images"]');
let formData = new FormData();
formData.append('images' , images.files[0] );
try {
const response = await fetch('http://exampleurl.com/profile', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': "<%= req.csrfToken() %>",
},
body: formData,
credentials: 'same-origin'
});
} catch (error) {
console.error(error);
}
})
</script>
I can't use method ="POST" and enctype= "multipart/form-data" in the form because csrf tokens can't implement in forms with multipart/form-data enctype
I suspect your form might be submitting twice.
1) AJAX event handler
2) The submit button in the form actually posting the form through html
Try adding the event handler to the form itself, rather than the submit button.
There you can prevent the form from doing what it wants to do so only your AJAX request will go through.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event

How do I console.log my POST. When i try to GET all i get in console is "null"

So here is my code. My POST function seems to work. But when I try to console.log my POST from the server all I get is "null".
What I need help with is to properly POST to my form to the server. And then be able to retrieve it and post it to to my console.
I then have to post it to my website, but that i can manage for myself.
const myForm = document.getElementById("myForm");
myForm.addEventListener("submit", function(e) {
e.preventDefault();
const formData = new FormData(this);
formData.append("store", "vetlekw1");
fetch("http://folk.ntnu.no/oeivindk/imt1441/storage/add.php?", {
method: "post",
body: formData
})
.then(function(response) {
return response.text();
})
.then(function(text) {
console.log(text);
});
});
document.querySelector(".hent").addEventListener('click', e=>{
fetch('http://folk.ntnu.no/oeivindk/imt1441/storage/getAll.php?store=vetlekw1')
.then(res=>res.json())
.then(data=>{
console.log(data);
})
})
<section id="addContact">
<h1>add Contact</h1>
<form class="form" id="myForm" >
<label for="fornavn">Name</label>
<input type="text" id="fornavn"><br>
<label for="etternavn">Surname</label>
<input type="text" id="etternavn"><br/>
<label for="tlf">Tlf</label>
<input type="text" id="tlf"><br>
<button type="submit">add</button>
</form>
</section>
<br>
<button class="hent">Get</button>
You don't give back the expected data from your server endpoint. Maybe your db query gives no result or you are using a wrong variable or something else.

Categories

Resources