Postman cannot connecto NodeJS server even if its running? - node.js

I wrote this code in my node app
const express = require("express");
const cors = require("cors");
const pool = require("./db");
const app = express();
//middleware
app.use(cors);
//access req.body
app.use(express.json());
app.get("/", async (req, res) => {
try {
res.json("response from server");
// const allCompanies = await pool.query("SELECT * FROM COMPANIES");
// res.json(allCompanies.rows);
} catch (error) {
console.log(error.message);
}
});
const port = 1337;
app.listen(port, () => {
console.log(`Server is starting on port ${port}`);
});
In my terminal it says its running on 1337 however when i try to connect to postman it leaves me hanging? never had this problem before.

const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
The problem was that you were not calling the cors function on your app.use middleware.
If you change the code to
app.use(cors());
It should work.
Express Documentation

Related

Express app on heroku throws authentication error on POST requests

The app works fine on GET requests. But on a POST request with body an application error occurs. I can't figure out this problem.
My app setup using express is like this:
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config()
const port = process.env.PORT || 5000
const app = express()
app.use(cors())
app.use(express.json())
app.get('/', (req, res) => {
res.send('Express Server Running...✔')
})
app.listen(port, () => {
console.log('Listening to port', port);
})

Cannot GET /api

I have a problem with my post data to the server. Not sure why i get an error for get when i changed my rout to post.
routes/feedback.js
const express = require("express");
const router = express.Router();
const { emailFeedback } = require("../controllers/feedback");
router.post("/feedback", emailFeedback);
module.exports = router;
server.js
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config();
// import routes
const feedbackRoutes = require("./routes/feedback");
// app
const app = express();
// middlewares
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cors());
// routes
app.use("/api", feedbackRoutes);
// port
const port = process.env.PORT || 8000;
app.listen(port, () => console.log(`Server is running on port ${port}`));
I believe the usual syntax for an express post route is as follows:
router.post("/feedback", function(req, res){
//grabbing the request body
console.log(req.body);
console.log(req.bodt);
//posting the request
res.json(req.body);
});
A callback function needs to be passed in and receive those request and response parameters (req, res).

nodejs graphql - localhost:3001 doesn't load

Loading localhost:3001 which worked for me before, stopped working for me all of a sudden. I am not seeing anything wrong on the code and I am getting server started message as well when run the server. But localhost:3001 doesn't seem to be loading.
here is the code -
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const cors = require('cors');//to have this api accessed by multiple domains
const dotEnv = require('dotenv');
dotEnv.config();
const app = express();
//middleware
app.use(cors);
app.use(express.json());
const typeDefs = gql`
type Query {
greetings: String
}
`;
const resolvers = {};
const apolloServer = new ApolloServer({
typeDefs,
resolvers
});
apolloServer.applyMiddleware({app, path: '/graphql'});
const PORT = process.env.PORT || 3000;
app.use('/', (req,res, next) => {
res.send({message: 'Hello Sumesh'});
});
app.listen(PORT, () => {
console.log(`Server listening on PORT: ${PORT}`);
console.log(`GraphQL Endpoint: ${apolloServer.graphqlPath}`);
});
Here is the terminal output when the server running -
Problem is with your cors middleware statement. It should be:
app.use(cors());
instead of
app.use(cors);

No request body recieved from api call

This is my server.js -
const express = require("express");
const connectDB = require("./api/config/db");
const feedbackRouter = require("./api/routes/feedbackRouter");
const app = express();
const PORT = process.env.PORT || 5000;
connectDB();
app.use(feedbackRouter);
app.listen(PORT, () => {
console.log(`SERVER IS LIVE AT ${PORT}`);
});
Router (feedbackRouter.js)-
const express = require("express");
const router = express.Router();
router.post("/feedback", (req, res) => {
const feedbackData = req.body;
try {
console.log(feedbackData);
res.send(feedbackData);
} catch (error) {
res.status(400).send(error);
}
});
module.exports = router;
When I make an API call from the frontend(React) or Postman, the req.body gives me undefined and I don't see the content from the request anywhere.
The API call gives me status code of 200 in Postman.
Any idea what might be wrong here? Thanks in advance.
Add app.use(express.json()) to your Code.
Server.js:
const express = require("express");
const connectDB = require("./api/config/db");
const feedbackRouter = require("./api/routes/feedbackRouter");
const app = express();
const PORT = process.env.PORT || 5000;
app.use(express.json())
connectDB();
app.use(feedbackRouter);
app.listen(PORT, () => {
console.log(`SERVER IS LIVE AT ${PORT}`);
});
About express.json() method and its options:
https://expressjs.com/en/5x/api.html
You didn't use any body-parsers, they use to process the body of an request, documentation:
http://expressjs.com/en/resources/middleware/body-parser.html
Postman Request & Response:

How to access my IPFS node instance from my express router

I can't seem to work out the correct approach for running a IPFS node in my express app (/services/IPFS.js), while also being able to access it within my routes (/routes/uploads.js)
/services/IPFS.js
const IPFS = require("ipfs-core");
module.exports = startNode = async (req, res, next) => {
console.log("Starting IPFS node...");
return await IPFS.create();
};
index.js
const express = require("express");
const bodyParser = require("body-parser");
const apiRouter = require("./routes/api");
const cors = require("cors");
const app = express();
const port = 4000;
const startNode = require("./services/IPFS");
app.use(cors());
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use("/api/v1", apiRouter);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
startNode();
How do I pass my IPFS instance through to /routes/upload.js so I can use ipfs.add(file) in my /upload endpoint?
Any help appreciated.
Thanks
You could define the apiRouter as a factory function and pass the startNode function to it. In your router you can then call it:
// in your index.js
// ...
app.use("/api/v1", apiRouter(startNode));
// ...
// in your apiRouter.js
const express = require('express');
const router = express.Router();
module.exports = (startNodeFn) => {
router.post('/upload', async (req, res) => {
const result = await startNodeFn.call(startNodeFn, req, res);
// handle result and do upload ...
});
// rest of routes
// ...
return router;
}

Resources