Jafar Isbarov
Jafar Isbarov

Reputation: 1562

Node.js - No body returned for response

This route is supposed to get a response from an external API, and return its body.

const router = require("express").Router();
import generateSudoku from '../components/sudoku_generator';

router.route('/:difficulty').get(async (req: any, res: any) => {
  const difficulty = req.params.difficulty

  generateSudoku(difficulty)
    .then(data => {
        res.json(data)
          .then('Sudoku generated.')
          .catch((err: string) => res.status(400).json('Error: ' + err));
    })
});

module.exports = router;

Here is the generateSudoku function:

import axios from 'axios';

const BASE_URL = 'https://sugoku.herokuapp.com/board?difficulty=';

const generateSudoku = (difficulty: string) => {

      return axios.get(`${BASE_URL}${difficulty}`)
              .then(function(response){
              this.response = response.data
              return this.response
            })
            .catch (err => console.error(err));
};

export default generateSudoku;

The problem is that GET request to http://localhost:5000/play/easy returns no body. What could be the problem? Edit:
Here is my app.tsx file:

const mongoose = require("mongoose");
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser')

require('dotenv').config();


const app = express();
const port = process.env.port || 5000;

app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())

//app.use(express.json);
app.use(cors())

const uri = process.env.ATLAS_URI;

mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true})
  .then(console.log("Database connected."))
  .catch((err: string) => console.log("Error: " + err));

const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully.")
})

const playRouter = require('./routes/play');
const recordsRouter = require('./routes/records');
const usersRouter = require('./routes/users')

app.use('/play', playRouter);
app.use('/records', recordsRouter);
app.use('/users', usersRouter)

app.listen(port, () => {
  console.log("Server is running.");
});

Upvotes: 0

Views: 2997

Answers (2)

cefn
cefn

Reputation: 3321

The following part seems wrong to me as commented inline below...

async (req: any, res: any) => {
  const difficulty = req.params.difficulty

  //no await for this promise
  generateSudoku(difficulty)
    .then(data => {
        res.json(data)
          //possible 'then' call on a non-promise
          .then('Sudoku generated.')
          .catch((err: string) => res.status(400).json('Error: ' + err));
    })
}

Perhaps the implied error from calling 'then' was being swallowed before since you weren't waiting for anything from the async function. I speculate replacing all of that with this async function might give you a result...

async (req: any, res: any) => {
  try{
    const data = await generateSudoku(req.params.difficulty);
    res.json(data);
    return 'Sudoku generated.';
  }
  catch(err){
    res.status(400).json('Error: ' + err)
  }
}

Upvotes: 2

František Žiačik
František Žiačik

Reputation: 7614

I think res.json doesn't return a promise, so i guess it just silently throws an error. Besides, what should .then('Sudoku generated') really do?

Try removing that part and move the catch out too

generateSudoku(difficulty)
    .then(data => res.json(data))
    .catch((err: string) => res.status(400).json('Error: ' + err));

Or, since you use an async, you don't need to use then, you can just write it like this:

try {
    const data = await generateSudoku(difficulty);
    res.json(data);
} catch(err) {
    res.status(400).json('Error: ' + err)
}

Upvotes: 1

Related Questions