Skip to content

Instantly share code, notes, and snippets.

@marcobehlerjetbrains
Last active May 17, 2024 18:10
Show Gist options
  • Save marcobehlerjetbrains/3b9ed46953f810160e3a47e81f88e027 to your computer and use it in GitHub Desktop.
Save marcobehlerjetbrains/3b9ed46953f810160e3a47e81f88e027 to your computer and use it in GitHub Desktop.
Spring Boot REF2 - Http Post
(async function createPhoto() {
let photo = {"fileName": "hello.jpg"};
await fetch("http://localhost:8080/photoz", {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(photo)
})
.then(result => result.text())
.then(text => alert(text));
})();
@adeshinadesola
Copy link

This works for me :

async function createPhoto() {
const photoData = {
fileName: "newphoto.jpg" // Update the filename here
};

try {
    const response = await fetch("http://localhost:8080/photoz/1", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(photoData)
    });

    if (!response.ok) {
        throw new Error("Failed to create photo");
    }

    const responseData = await response.json();
    console.log("Photo created successfully:", responseData);
} catch (error) {
    console.error("Error:", error.message);
    alert("Error occurred while creating photo");
}

}

createPhoto();

you should get this return :

{"id":"1","fileName":"hello.jpg"},{"id":"39be5f8d-71d1-4483-b8e9-50619dc01632","fileName":"hello.jpg"}]

and also add @requestbody annotation to postmapping

@palakkalsi
Copy link

Using postman works for me.
https://www.postman.com/downloads/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment