I'm sending a POST request to my Node.js server, but the body returned in the fetch response is null.
export default class PanelAddProd extends React.Component<any, IState>{
state: IState = {
"url": 'http://localhost:3000/products',
name: 'e2334r23',
desc: 'r2dfsdfwqewqedf',
price: 44,
}
updateName = (e: React.FormEvent<HTMLInputElement>) => {
this.setState({name: e.currentTarget.value});
}
updateDesc = (e: React.FormEvent<HTMLTextAreaElement>) => {
this.setState({desc: e.currentTarget.value});
}
updatePrice = (e: React.FormEvent<HTMLInputElement>) => {
this.setState({price: Number(e.currentTarget.value)});
}
addProduct = async (e: React.FormEvent<HTMLInputElement>) => {
e.preventDefault();
const data = JSON.stringify({
name: this.state.name,
description: this.state.desc,
price: this.state.price,
});
const fetchOpts = {
body: data,
method: 'POST', // or 'PUT'
mode: 'no-cors' as RequestMode,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
};
try {
console.log('Fetch data ', data);
const response = await fetch(this.state.url, fetchOpts);
console.log('Fetch response ', response);
return response;
} catch (error) {
console.log('Fetch error ', error);
}
}
Server side code:
import { Controller, Body, Post } from "@nestjs/common";
import { ProductsService } from "./products.service";
@Controller('products')
export class ProductsController{
constructor(private readonly productsService: ProductsService) {}
@Post()
async addProduct(@Body('name') prodTitle: string, @Body('description') prodDesc: string, @Body('price') prodPrice: number) {
console.log('---------------------------------------------------------------------');
console.log('Adding product...', prodTitle, prodDesc, prodPrice);
const generatedId = await this.productsService.insertProduct(
prodTitle,
prodDesc,
prodPrice
);
console.log('Product added', generatedId);
return { id: generatedId };
}
}
In try, console.log data has value, but response.body is null. My nodeJS server reacts to request, but as expected doesn't get any data and its console.log write all variables as unidentifieds.