I am currently using Symfony like an API with API platform. In my JavaScript I did a connection to my HTML form using the method POST.
here's the form:
<h1>créer un article</h1>
<form action="" method="post">
<div>
<label for="title"> Titre: </label>
<input type="text" name="title" id="formTitle">
</div>
<div>
<label for="body">Body: </label>
<input type="text" name="body" id="formBody">
</div>
<div>
<label for="tags">Tags: </label>
<input type="text" id="formTags">
</div>
<div>
<label for="category">Category: </label>
<input type="text" name="category" id="formCategory">
</div>
<div>
<label for="writer"> auteur:</label>
<input type="text" id="formWriter">
</div>
<div>
<label for="date"> date:</label>
<input type="date" id="formDate">
</div>
</form>
<button id="submit">
créer l'article
</button>
<button id="submitLocal">
créer l'article en local
</button>
here's my method:
function send() {
//paramètres enregistrés en BDD
var parameters = {
"title": getTitle.value,
"body": getBody.value,
"tags": [
getTags.value
],
"writer": getWriter.value,
"publishedAt": getDate.value
}
/*je fetche l'URL en paramètre de ma variable fetchURL, le header est l'une des conditions d'un CORS
fonctionnel, l'autre*/
fetch(fetchURL, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(parameters)
})
.then((response) => response.json)
.then(function(articles) {
console.log(articles)
})
}
//fonction d'envoi des informations dans le localstorage
function sendToLocal() {
/*envoi des données dans le localStorage de manière persistente
(à la différence ud sessionStorage qui s'efface à chaque reouverture)*/
localStorage.setItem("titre", getTitle.value)
let titleItem = localStorage.getItem("titre")
localStorage.setItem("Body", getBody.value)
let bodyItem = localStorage.getItem("body")
localStorage.setItem("tags", getTags.value)
let TagsItem = localStorage.getItem("tags")
localStorage.setItem("writer", getWriter.value)
let writerItem = localStorage.getItem("writer")
localStorage.setItem("date", getDate.value)
let dateItem = localStorage.getItem("date")
//faire de la gestion d'erreurs
}
and here's how it's shown in API platform (note: check the parameters variable to compare):
{
"title": "string",
"body": "string",
"tags": [
"string"
],
"category": "string",
"writer": "string",
"publishedAt": "2022-08-10T20:37:24.541Z"
}
for the DOM, I used a querySelector 2 addEventListeners placed after the function send. However it sends me an error 400 bad request, even if the parameters are exactly the same. So the connection to the API is ok, but not the request. Can someone help me solve this?
CodePudding user response:
if your resource has relationship with tags
use IRIs instead,
{
"title": "string",
"body": "string",
"tags": [
"api/tags/1"
],
"category": "string",
"writer": "string",
"publishedAt": "2022-08-10T20:37:24.541Z"
}