I want to get my data using using express. Here's the code:
const express = require('express');
const app = express();
const cors = require('cors');
require('dotenv/config');
// Middlewares
app.use(cors());
app.use(express.json());
// Routes
const postRouter = require('./routes/posts');
app.use('/posts', postRouter);
// Mongoose connect
const mongoose = require('mongoose');
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
() => console.log("You are connected to MongoDB")
);
// Port listen
app.listen(2998);
These node+express code works perfect using Postman.
But it always show CORS error when im fetching using javascript. Here's the JS code:
let url = "https://localhost:2998/posts/"
fetch(url)
.then(result => {
console.log(result);
})
.then(data => {
console.log("data: " + data)
});
And the console says:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:2998/posts/. (Reason: CORS request did not succeed).
. . . . .
SOLVED ! It just can't run the https protocol, so i need to change it to http://localhost/2998. Still, I don't know why it happen to be like that