I have an issue when i am trying to post to my API (Net6.0) because i get the error of 400 fetch, i have tried different things that i have found on here but i cant seem to fix it.
Here is my code:
my function:
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [link, setLink] = useState('');
const handleSubmit =(e) => {
e.preventDefault();
const post = { title, description, link };
fetch('https://localhost:7018/api/Posts', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(post)
}).then(() => {
console.log('new post added');
// GoBack()
})
}
and my return:
<div className="create">
<form onSubmit={handleSubmit}>
<label>Titel</label>
<input
type="text"
required
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<label>Description</label>
<textarea
required
value={description}
onChange={(e) => setDescription(e.target.value)}
></textarea>
<label>Link</label>
<input
type="text"
required
value={link}
onChange={(e) => setLink(e.target.value)}
/>
<button>Skapa Inlägg</button>
<p>{ title }</p>
<p>{ description }</p>
<p>{ link }</p>
</form>
</div>
here is the error code i get
[1]: https://i.stack.imgur.com/WHwTn.png
Related
I'm trying to submit post form data to an my api using react and I'm passing through JSON data like so.
`
function AddSong() {
const [title, setTitle] = useState("");
const [artist, setArtist] = useState("");
const [release_date, setReleaseDate] = useState("");
const [album, setAlbum] = useState("");
const [genre, setGenre] = useState("");
let handleSubmit = async (e) => {
e.preventDefault();
try {
let res = await fetch("http://127.0.0.1:8000/api/music_library/?format=json", {
method: "POST",
body: JSON.stringify({
title: title,
artist: artist,
album: album,
release_date: release_date,
genre: genre,
}),
});
let resJson = await res.json();
if (res.status === 200) {
setTitle("");
setArtist("");
setReleaseDate("");
setAlbum("");
setGenre("");
}
} catch (err) {
console.log(err);
}
};
`
Here is my submit form.
`
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input
type="text"
value={title}
placeholder="Title"
onChange={(e) => setTitle(e.target.value)}
/>
<input
type="text"
value={artist}
placeholder="Artist"
onChange={(e) => setArtist(e.target.value)}
/>
<input
type="text"
value={release_date}
placeholder="Year"
onChange={(e) => setReleaseDate(e.target.value)}
/>
<input
type="text"
value={album}
placeholder="Album"
onChange={(e) => setAlbum(e.target.value)}
/>
<input
type="text"
value={genre}
placeholder="Genre"
onChange={(e) => setGenre(e.target.value)}
/>
<button type="submit">Create</button>
</form>
</div>
);
}
export default AddSong;
`
When I click submit on the form, Chrome gives me an error saying "Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)". I know it has something to do with the HandleSubmit function and the url im giving it. Im just not sure how to structure it correctly.
I tried going to the django api website and changing the get request url to JSON. I was expecting that accept the JSON data im passing through however it did not and instead gave me the same error I got when using the regular url.
I have a React app in front-end with ASP.NET Web Api in back-end. When I try to make a PUT request from React to Web Api in the console appears error with number 400. With all other requests everything is fine. I put a breakpoint in ASP.NET in debug but even then request doesn't get in Web API.
This is my code in React:
import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './editContact.module.css';
const EditContact = () => {
const id = window.location.pathname.slice(14);
const navigate = useNavigate();
const [contactName, setContactName] = useState('');
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
const [description, setDescription] = useState('');
const [categories, setCategories] = useState('');
const [areas, setAreas] = useState('');
const [event, setEvent] = useState('');
const [continent, setContinent] = useState('');
const [country, setCountry] = useState('');
const getContact = useCallback (async () => {
const request = await fetch(`https://localhost:7082/api/contacts/${id}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
const response = await request.json();
setContactName(response.name);
setEmail(response.email);
setAreas(response.areas);
setCategories(response.categories);
setDescription(response.description);
setEvent(response.event);
setPhone(response.phoneNumber);
setContinent(response.continent);
setCountry(response.country);
}, [id]);
const sendToHome = () => {
navigate('/');
};
const editContact = async (e) => {
e.preventDefault();
await fetch(`https://localhost:7082/api/contacts/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
contactName,
email,
phone,
description,
areas,
event,
categories,
continent,
country
})
})
.then(() => {
navigate('/');
})
.catch((e) => {
alert(e.message);
})
};
useEffect(() => {
getContact();
}, [getContact]);
return (
<form className={styles.form} onSubmit={editContact}>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Name</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setContactName(e.target.value)} value={contactName} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">eMail</label>
<input type="email" className="form-control" id="exampleFormControlInput1" onChange={e => setEmail(e.target.value)} value={email} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Phone</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setPhone(e.target.value)} value={phone} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Description</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setDescription(e.target.value)} value={description} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Categories</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setCategories(e.target.value)} value={categories} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Areas</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setAreas(e.target.value)} value={areas} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Event</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setEvent(e.target.value)} value={event} />
</div>
<button type='submit' className='btn btn-success mt-5' style={{ marginRight: 5 + 'px' }} name='edit'>Submit</button>
<button className='btn btn-secondary mt-5' onClick={sendToHome}>Cancel</button>
</form>
);
};
export default EditContact;
And this is my code in ASP.NET:
[Route("api/[controller]")]
[ApiController]
public class ContactsController : ControllerBase
{
private readonly IContactsService contactsService;
public ContactsController(IContactsService contactsService)
{
this.contactsService = contactsService;
}
[HttpGet]
public JsonResult AllContacts()
{
var result = this.contactsService.GetAllContacts();
return new JsonResult(result);
}
[HttpGet("{id}")]
public JsonResult ContactDetails(string id)
{
var result = this.contactsService.GetContactDetails(id);
return new JsonResult(result);
}
[HttpPost]
public ActionResult AddContact(AddContactViewModel model)
{
if (!this.ModelState.IsValid)
{
return this.BadRequest();
}
this.contactsService.AddContact(model);
return this.Ok();
}
[HttpPut("{id}")]
public ActionResult EditContact(string id, EditContactViewModel model)
{
this.contactsService.EditContact(id, model);
return this.Ok();
}
}
I will happy if someone could help me.
I have a problem with my code. I have a tag with options, when I try to set contact type set contact type appears white screen with error in the console "types.map() is not a function" white screen with errors. I think the problem comes from that at the beginning "types" are array and when I choose contact type with the state() "types" become a single value. I don't know how to fix that.
This is my code:
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import styles from './postContact.module.css';
const PostContact = () => {
const [nickName, setNickName] = useState('');
const [address, setAddress] = useState('');
const [phoneNumber, setPhoneNumber] = useState('');
const [account, setAccount] = useState('');
const [types, setType] = useState([]);
const navigate = useNavigate();
const postContact = async (e) => {
e.preventDefault();
await fetch('http://localhost:5090/api/contacts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
nickName,
address,
phoneNumber,
userId: 1,
contactTypeId: types,
account
})
})
.then(() => {
navigate('/');
})
.catch((e) => {
alert(e.message)
});
};
const getTypes = async () => {
const request = await fetch('http://localhost:5090/api/contactTypes', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
const response = await request.json();
setType(response);
};
useEffect(() => {
getTypes();
}, []);
return (
<form className={styles['post-form']} onSubmit={postContact}>
<label htmlFor='nickName'>Nickname</label>
<input className={styles.input} id='nickName' type='text' onChange={e => setNickName(e.target.value)} value={nickName} />
<label htmlFor='address'>Address</label>
<textarea className={styles.input} id='address' type='text' onChange={e => setAddress(e.target.value)} value={address} />
<label htmlFor='phoneNumber'>Phone Number</label>
<input className={styles.input} id='phoneNumber' type='text' onChange={e => setPhoneNumber(e.target.value)} value={phoneNumber} />
<label htmlFor='account'>Account</label>
<input className={styles.input} id='account' type='text' onChange={e => setAccount(e.target.value)} value={account} />
<label htmlFor="type">Contact Type</label>
<select className={styles.input} title="type" name="type" onChange={e => setType(e.target.value)} value={types}>
{types.map(type=>
<option key={type.id} value={type.id}>{type.type}</option>
)}
</select>
<button className="btn btn-primary mt-5" type='submit' name='Post'>Create</button>
</form>
);
};
export default PostContact;
I'll be grateful if anyone can help me.
On the first render the value for types will be undefined ( on sync code execution ), try using it as
<select className={styles.input} title="type" name="type" onChange={e => setType(e.target.value)} value={types}>
{types?.map(type=>
<option key={type.id} value={type.id}>{type.type}</option>
)}
</select>
? will make sure to run map once value for types is there ( also make sure it is mappable ( is an array ))
Handle the array falsy cases before doing any operations on it
<select
className={styles.input}
title="type" name="type"
onChange={e => setType(e.target.value)}
value={types}
>
{types.length && types.map(type=>
<option key={type.id} value={type.id}>{type.type}</option>
)}
</select>
I'm trying to post multiple variables to my Postgres database using a form with React.
This is my current script:
const InputAddress = () => {
const [name, setName] = useState("");
const [problem, setProblem] = useState("");
const [date, setDate] = useState("");
const onSubmitForm = async (e) => {
e.preventDefault();
try {
const body = {
name,
problem,
date,
};
console.log(params);
const response = await fetch("http://localhost:5000/logements", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
console.log(response);
window.location = "/";
} catch (error) {
console.log(error.message);
}
};
return (
<Fragment>
<h1 className="text-center mt-5">Add your address</h1>
<form className="d-flex mt-5" onSubmit={onSubmitForm}>
<label>Name</label>
<input
type="text"
className="form-control"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<label>Comment</label>
<input
type="text"
className="form-control"
value={problem}
onChange={(e) => setProblem(e.target.value)}
/>
<label>Date</label>
<input
type="text"
className="form-control"
value={date}
onChange={(e) => setDate(e.target.value)}
/>
<button className="btn btn-success">Submit</button>
</form>
</Fragment>
);
};
My problem seems to be with the fetch method.
When I submit the form, I get this error message in the console :
bind message supplies 1 parameters, but prepared statement "" requires 3
Is there a simple fix to this problem?
Im making a personal website for training and I wanted to use Netlify form submission for /contact URL I tried adding just netlify , netlify='true', and other things like that but i just gives me 404 error everytime im trying to use Netlify form submission, but it doesnt seem to work no matter what I do, I followed several tutorials and repos but still does not work. It just gives 404 error and other stuff;
and please check my github repo,
My GitHub Repo's Link
and here is my Contact.js component;
import React, { Fragment, useState } from 'react';
import '../../App.css';
const encode = (data) => {
return Object.keys(data)
.map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
.join('&');
};
const Contact = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [text, setText] = useState('');
const handleSubmit = (e) => {
fetch('/', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: encode({
'form-name': 'contact',
name: name,
email: email,
text: text,
}),
})
.then((res) => {
console.log(res);
})
.catch((error) => alert(error));
e.preventDefault();
};
return (
<Fragment>
<div className='contact'>
<div className='contact-wrapper'>
<div className='title'>
<span>Contact me</span>
</div>
<div className='contact-form'>
<form
className='myform'
method='POST'
name='contact'
data-netlify='true'
onSubmit={(e) => handleSubmit(e)}
>
<input type='hidden' name='form-name' value='contact'></input>
<input
type='text'
placeholder='Your Name'
name='name'
value={name}
onChange={(e) => setName(e.target.value)}
></input>
<input
type='email'
placeholder='Your E-Mail'
name='email'
value={email}
onChange={(e) => setEmail(e.target.value)}
></input>
<textarea
placeholder='Your message'
name='message'
value={text}
onChange={(e) => setText(e.target.value)}
></textarea>
<button type='submit'>Send</button>
</form>
</div>
</div>
</div>
</Fragment>
);
};
export default Contact;
Netlify's forms work by their servers editing your html at deploy to add in their hooks for submitting the form.
With a React app, the form will not be visible in the html at deploy, so this won't work.
Netlify have a guide for how to set up their forms with SPAs, view it here: https://www.netlify.com/blog/2017/07/20/how-to-integrate-netlifys-form-handling-in-a-react-app/