How does the fetch api work with express when trying to send a json object

Viewed 676

I have a system in place where I have a nodejs app:

app.post('/action', (req, res) => {
 ...
const option = req.body.option
 ...
switch (option) {
    case 'getinfo':
        objectToSend = {"foo": "bar"}
        // i tried using
        res.json(objectToSend)
        // and
        res.send(JSON.stringify(objectToSend))
        // but neither got me anywhere
    break
}

And a website that sends a post request using fetch like this (infoModal is the function I use to display data) (I got the action function sent on discord and have been using it since then, but ive never had to do anything with the response)

let action = async (i) => {
    res = await fetch("/action", {
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        method: "POST",
        body: JSON.stringify(i)
    })
    return await res.json
}
action({
            option: 'getinfo'
        }).then(j => {
            infoModal(j.foo,'ok')
        })

I can't really fix either the backend or frontend since both have to work for me to confirm it works...

EDIT: These are my requires, uses and sets:

require('dotenv').config()
 ...
const express = require('express')
const path = require('path')
var bodyParser = require('body-parser')
let ejs = require('ejs')
const fs = require('fs')
var cookieParser = require('cookie-parser')
var colors = require('colors')

const app = express()

app.use(bodyParser.json())
app.use(cookieParser())

app.set('views', path.join(__dirname, 'frontend'))
app.set('view engine', 'ejs')
1 Answers

One obvious mistake is not executing the jeson() method of the Fetch response. And, although harmless, the second await statement is not really necessary - the async functions anyway wrap what is returned in a promise.

return res.json();

If that doesn't work -

  1. See what your developer console says. It should give you lot of information about the request. If there is an error, follow the info (response code, any error message etc) and try to determine the problem.

  2. Use a rest client such as POSTMAN to verify your backend first. When you know that it can respond well to a proper request, you can try your front-end with confidence and get more understanding on how the response should be handled.

Related