0

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.

Arphik
  • 1
  • 1
  • 1
    Can you please also show your server side code? – Chaim Friedman Nov 04 '20 at 15:58
  • Read [this article](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) for tips on debugging your code. – Code-Apprentice Nov 04 '20 at 16:00
  • In `body: data` , data passed in body should be an object. I can see here you are `stringifying` the data and then passing into body. – Akanksha singh Nov 04 '20 at 16:38
  • Stringifying is necessary, for types valid, I want sent by fetch json type like here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch – Arphik Nov 04 '20 at 16:52
  • Right. Please show your server side code. – Akanksha singh Nov 04 '20 at 16:59
  • I added server code. – Arphik Nov 05 '20 at 18:13
  • I solved problem. It was a matter of CORS, I changed 'no-cors' to 'cors' in fetch and in nestJS server I added parameter to accept CORS. async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors(); <-------------------------- await app.listen(3000); } bootstrap(); – Arphik Nov 07 '20 at 17:33

0 Answers0