I’ve tried to post data from FrontEnd with ReactJS to BackEnd Spring Boot but it has AxiosError: Request failed with status code 500
could you guy tell what wrong with my code? why i can’t post new product to backend?
here is my code:
BackEnd:
Product Controller
package com.tranxuanphong.example04.controller;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.tranxuanphong.example04.entity.Product;
import com.tranxuanphong.example04.service.ProductService;
import lombok.AllArgsConstructor;
@RestController
@AllArgsConstructor
@RequestMapping("api/products")
@CrossOrigin(origins = { "http://localhost:3000"}, exposedHeaders = "Content-Range")
public class ProductController {
private ProductService productService;
// Create Product REST API
@PostMapping
public ResponseEntity<Product> createProduct(@RequestBody Product product) {
Product savedProduct = productService.createProduct(product);
return new ResponseEntity<>(savedProduct, HttpStatus.CREATED);
}
// Get All Products REST API
// http://localhost:8080/api/Products
@GetMapping
public ResponseEntity<List<Product>> getAllProducts() {
List<Product> products = productService.getAllProducts();
return new ResponseEntity<>(products, HttpStatus.OK);
}
}
React: Product.js
const createProduct = (event) => {
event.preventDefault();
if (title !== "" || body!== "" || price !== "" || category !== "0" || photo !== "") {
let product = {
title: title,
description: body,
price: price,
photo: photo,
category_id: parseInt(category)
}
POST_ADD_PRODUCT(`products`, product).then(item => {
// console.log('item:',item);
if(item.data===1){
setCheckAdd(true);
}
})
}
else {
alert("Not enough information");
}
}
React: apiService.js
export function callApi(endpoint, method = 'GET', body) {
return axios({
method: method,
url : `${API_URL}/${endpoint}`,
data : body,
})
.catch(e => {
console.log(e)
})
}
export function POST_ADD_PRODUCT (endpoint, data) {
return callApi(endpoint, "POST", data);
}
i’ve been trying to post this from my FrontEnd ReactJS to BackEnd all day but i can’t
however I tried Postman and it worked fine with post and get
so i think my FrontEnd have some problem maybe
Peter Just Peter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.