0

I'm using Typescript Fetch wrapper to do post and get requests and getting empty object on post(get works fine) (Before I used Vanilla Js and all worked fine) Nodejs:

const express = require('express');
const fs = require('fs');
const app = express();
app.use(function (req, res, next) {
 res.header('Access-Control-Allow-Origin', '*');
 res.header(
 'Access-Control-Allow-Headers',
 'Origin, X-Requested-With, Content-Type, Accept'
 );
 next();
});
app.use(express.json());
app.post('/login', (req, res) => {
 let isLogged = login(req.body);
 console.log(req.body);
 res.status(200).json(isLogged);
});

My Typescript fetch Wrapper:

async function fetchWrapper<T>(path: string, config: RequestInit): Promise<T> {
 const request = new Request(path, config);
 const response = await fetch(request);
 if (!response.ok) {
 throw new Error(
 `name: ${response.status}, message: ${response.statusText}`
 );
 }
 // return empty object
 return response.json().catch(() => ({}));
}
 
export async function post<T, U>(
 path: string,
 body: T,
 config?: RequestInit
): Promise<U> {
 const init = { method: 'post', body: JSON.stringify(body), ...config };
 return await fetchWrapper<U>(path, init);
}

my post request:

 const res = await fetch.post(`${url}/login`, {
 body: inputData,
 headers: { 'Content-Type': 'application/json' },
 });

input data is not empty

asked Oct 31, 2021 at 15:24

1 Answer 1

3

The problem here that you are using wrong Content-Type header value. express.json parses application/json content type, while you are sending application/x-www-form-urlencoded. The solution is either to change the content-type you are sending, or add another middleware like bodyparser to parse application/x-www-form-urlencoded body.

answered Oct 31, 2021 at 15:28
Sign up to request clarification or add additional context in comments.

3 Comments

I changed it but get same results(
What have you changed?
'application/json'. My mistake was that I didn't pass parameters for fetch.put correctly, so I changed the wrapper and all worked for me

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.