I'm testing a Node.js back end, which connects to MongoDB.
The Node/MonogoDB connection is fine - when I enter http://localhost:3000/stories
in the browser it shows the response with data from the DB.
But when testing on Postman, nothing comes back: Error: CORS request rejected: http://localhost:3000/stories
Here's the controller:
const { getCollection } = require('./service/DatabaseService')
const { ObjectId } = require('mongodb')
const handleOptionsRequest = async (request, response) => {
response.status(200).send()
}
const getStory = async (request, response) => {
const collection = await getCollection("Project", "Collection")
let data = await collection.find({}).toArray()
console.log(data)
return response.status(200).json({
message: "Successfully retrieved story",
data: data,
})
}
module.exports = { getStory, handleOptionsRequest }
and index.js
const { routes } = require('./routes.js')
const express = require('express')
const app = express()
const port = 3000
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(function (request, response, next) {
response.header("Access-Control-Allow-Origin", "*")
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
response.header("Access-Control-Allow-Methods", "GET", "OPTIONS")
next()
})
routes(app)
app.listen(port)
I tried logging the variables, request and response to the terminal.
When Postman is sending its request to Node, the function in the controller runs and does log the data from the DB to the terminal.
But it can't get through to Postman!
Any ideas?
It is a cors
issue. If you want to allow cors
then install cors package using npm i cors
and then use app.use(cors())
.
const express = require('express')
const cors= require('cors');
const app = express();
const port = 3000;
app.use(cors());
app.use(express.json())
app.get('/',(req, res)=>{
// Do something here, send response
});
app.listen(port);