Me encuentro con estos problemas, espero me puedan ayudar. Según puedo ver, todo está bien y no entiendo porque no me permite guardar. Adjuntaré estos errores:
El campo doctorProfileImg
en mi base de datos (SQL Server) es de tipo varbinary(max)
y el otro campo es de tipo string
. Intento guardar esto desde React , además de otros campos claro.
y finalmente les dejo mi código: POST Controller
// POST: api/TDoctors
[HttpPost]
public async Task <IActionResult> PostTDoctor([FromBody] TDoctor tDoctor) {
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
_context.TDoctor.Add(tDoctor);
await _context.SaveChangesAsync();
return CreatedAtAction("GetTDoctor", new { id = tDoctor.DoctorId }, tDoctor);
}
En el modelo está así:
public byte[] DoctorProfileImg { get; set; }
public string DoctorPhoneNumber { get; set; }
Cargo los datos de los inputs en el state de esta forma:
handleChange = (e) => {
const state = this.state;
state[e.target.name] = e.target.value;
this.setState({
...state,
});
};
handleFileChange = (event) => {
this.setState({
file: URL.createObjectURL(event.target.files[0]),
});
};
handleSubmit = (e) => {
e.preventDefault();
const URL = "http://localhost:55317/api/TDoctors/";
const DATA = {
doctorName: this.state.name,
doctorProfileImg: this.state.file,
doctorPhoneNumber: this.state.phoneNumber,
doctorEmail: this.state.email,
doctorStatus: this.state.status,
doctorSpecialtyId: Number(this.state.specialty),
};
ApiService.post(URL, DATA)
.then(() => this.props.history.push("/doctors"))
.catch((err) => console.log(err));
};
En cuanto al ApiService , está creado de esta forma:
static post = async (url, obj) => {
const options = {
method: "POST",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(obj)
};
const response = await fetch(url, options);
const data = await response.json();
return data;
};
El error que me sale en la consola del navegador, es este:
> ApiService.js:50 POST http://localhost:55317/api/TDoctors/ 400 (Bad Request)
push../src/services/ApiService.js.ApiService.post @ ApiService.js:50
AddDoctor.handleSubmit @ AddDoctor.js:62
A qué se debe el problema?? no encuentro la solución a esto. En cuanto a doctorPhoneNumber
, más aún no encuentro razón, porque solo es de tipo texto... he revisado en el React Developers Tools , y los datos se cargan correctamente en el state , la imagen en formato blob y tenía entendido que el varbinary(max)
es una forma "moderna" de cargar datos blob en SQL Server.
Espero me puedan ayudar por favor. Muchas gracias.