I'm totally fresh at the back-end, right now learning Fron-End but decided to create my own server with Node.js. I installed Express, Cors, and Axios. It seems that it is working since I can see response from API in my terminal but I cannot make a GET request to fire up my machine.
How can I call the GET method? Now data from API is printed in terminal only, on Back-end I get this error:
**GET http://localhost:3002/ 404 (Not Found)
My back-end code:
const express = require('express');
const bodyParser = require('body-parser');
const router = require('express').Router();
var cors = require('cors');
const axios = require('axios').default;
const app = express();
app.use(cors())
axios.get('https://rickandmortyapi.com/api/character').then(res => {
console.log(res.data);
});
app.use('/', router);
app.use(bodyParser.json());
app.listen(3002, () => {
console.log(`Port is dummy. At least it started.`);
});
CodePudding user response:
Here how you can do it :
const express = require('express');
const bodyParser = require('body-parser');
const router = require('express').Router();
var cors = require('cors');
const axios = require('axios').default;
const app = express();
app.use(cors())
let data;
axios.get('https://rickandmortyapi.com/api/character').then(res => {
data = res.data;
});
router.get('/', (req, res) => {
res.send(data);
});
app.use('/', router);
app.use(bodyParser.json());
app.listen(3002, () => {
console.log(`Port is dummy. At least it started.`);
});
you need to call the router methods, like .get() to define your routes, when you do app.use('/', router)
it will just use your router, but it will not add a new route to your router, and since it's an empty router you get a 404
in your case app.use('/', router);
is the same as app.use(router);
, you don't need to specify it when it's /
, it's only useful for things like /clients
when you want to prefix your routes
CodePudding user response:
You should specify the get
endpoint in your app.
You can do it either using the Express Router:
const router = require('express').Router();
router.get('/', async (req, res) => {
try {
const { data } = axios.get('https://rickandmortyapi.com/api/character');
res.status(200).json(data)
} catch (err) {
res.status(500).json({ message: 'Server error' })
}
});
app.use('/', router);
Or using only Express:
app.get('/', async (req, res) => {
try {
const { data } = axios.get('https://rickandmortyapi.com/api/character');
res.status(200).json(data)
} catch (err) {
res.status(500).json({ message: 'Server error' })
}
})
Finally, note that body-parser
is deprecated, you should use:
const express = require('express');;
const app = express();
var cors = require('cors');
app.use(cors());
app.use(express.json());
...