Reputation: 472
So I am fairly new to the backend. Anyway, I want to create an API that I can use in the front-end, the error I am facing when I try to send a request to the localhost:5000/elements
Postman is giving me Error: connect ECONNREFUSED 127.0.0.1:5000
if someone could help me it would be awesome. Thanks
var fs=require('fs');
var data=fs.readFileSync('books.json');
var elements=JSON.parse(data);
const express = require("express");
const app = express();
const cors=require('cors');
const Port = 5000
app.listen(process.env.Port, () => console.log("Server Start at " + Port));
app.use(express.static('public'));
app.use(cors());
app.get('/elements',alldata);
function alldata(request,response)
{
response.send(elements);
}
app.get('/elements/:element/',searchElement);
function searchElement(request,response)
{
var word=request.params.element;
word=word.charAt(0).toUpperCase()+word.slice(1).toLowerCase();
console.log(word);
console.log(elements[word]);
if(elements[word])
{
var reply=elements[word];
}
else
{
var reply={
status:"Not Found"
}
}
console.log(reply.boil);
response.send(reply);
}
Upvotes: 0
Views: 182
Reputation: 16453
process.env.Port
is unrelated to Port
.
It's
app.listen(Port, () => console.log("Server Start at " + Port));
Upvotes: 1
Reputation: 2863
This problem usually happens if you forget to run npm start
.
Either way, I recommend moving the app.listen
to the bottom of the code. It helps with readability, and it will mount all of code before running the Express server.
Your process.env.Port
is also undefined. Change it to const port = process.env.Port || 5000
so you can get a fallback value. Change it also in the app.listen
.
Then, define allData
and searchElement
so they are located before the app.get('/elements')
. Finally, after you have done all of this, make sure that the request type in Postman is GET
.
Upvotes: 1