David Wisenberg
David Wisenberg

Reputation: 1

What am I doing incorrectly with my https request?

I'm learning how to build a RESTful api with Node and Express, and I am having an issue with this https request. I am trying to make a GET request to Scryfall's api (documentation here: https://scryfall.com/docs/api), but whenever I run my server and check the browser I get a message stating

"localhost didn’t send any data. ERR_EMPTY_RESPONSE".

As I'm new to using Node and Express, I'm not really sure what I am doing wrong. Here is the code for my server.js and app.js files.

//server.js
const https = require('https');
const app = require('./backend/app');

const port = process.env.PORT || '3000';

app.set('port', port);
const server = https.createServer(app); //pass the express app to the server

server.listen(port);

and

//app.js
const express = require('express');
const app = express();

app.use((req, res, next) => {
  console.log('This is the first middleware');
  next();
});

app.get('https://api.scryfall.com/cards/named?fuzzy=aust+com', (req, res, next) => {
    res.send('${res.body.name} is the name of the card!');
});

module.exports = app;

Any help would be greatly appreciated! Thanks in advance!

Upvotes: 0

Views: 90

Answers (2)

Darshana Pathum
Darshana Pathum

Reputation: 669

You can easily make a get request like this.

const express = require('express');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');

//Expect a JSON body
app.use(bodyParser.json({
    limit: '50mb'                   //Request size - 50MB
}));

app.get('/test', (req, res, next) => {

    // do whatever you need here
    res.status(200).send("ok");

});

app.listen(port, function () {
    console.log(`Server is running.Point your browser to: http://localhost:${port}`)
});

Upvotes: 0

Titus Sutio Fanpula
Titus Sutio Fanpula

Reputation: 3613

👨‍🏫 For an example, you can do it with this code below 👇:

const express = require('express');
const axios = require('axios');

const app = express();

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

app.use((req, res, next) => {
  console.log('This is the first middleware');
  next();
});

app.get('/', async (req, res, next) => {
    try {
      const result = await axios.get('https://api.scryfall.com/cards/named?fuzzy=aust+com');
      res.status(200).send(result.data);
    }catch(ex) {
      console.log(ex.message);
    }
});

app.listen(3000, () => {
  console.log('Server is up');
})

💡 From the code above, you can call the endpoint: localhost:3000 and than you will get the result.

I hope it's can help you 🙏.

Upvotes: 1

Related Questions