I'm learning javascript and express. I have already made backend applications that worked correctly, but I don't know how to send a request from a browser and receive the response from the server. This is a simple example of what I have tried:
server.js:
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("Listening on port 3000!")
})
app.get("/", (req, res) => {
res.send("Hello");
})
The server is on the glitch.com platform. When I go to the https://expressjs-test.glitch.me/ project from my browser, I see the Hello
message in the HTML document (it works correctly).
Javascript file executed from my browser:
let req = fetch("https://expressjs-test.glitch.me/");
req.then(response => console.log(response));
The problem I get when I try to do this is:
Access to fetch at 'https://expressjs-test.glitch.me/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I've seen other questions on stackoverflow and other sites but didn't understand how to fix this cors error.
Thank you for your time. Sorry if I made a mistake in this post.
CodePudding user response:
When you host your application on glitch.com
, You need to allow the access to the domains i.e what domain can access your backend. Once you do that you will be able to receive data from the API.
You can also add chrome cors plugin for the time being and enable it. After enabling it, reload the web page and you will be able to see the response.
Another way of testing or fetching data from the API, you can use PostMan or if using Visual Studio code, you can user thunder client from market place.
If there is settings in the console, I recommend you adding cors to your Node.js server.
const express = require("express"),
app = express(),
cors = require("cors"), // importing the `cors` package
const whitelist = ['http://example1.com', 'http://example2.com']
const corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use(cors(corsOptions)) // tells Express to use `cors`, and solves the issue
app.listen(3000, () => {
console.log("Listening on port 3000!")
})
app.get("/", (req, res) => {
res.send("Hello");
})
You should check the cors documentation here and there is another link for glitch cors issue.
CodePudding user response:
You need to use cors
in your app. So it can be accessed from frontend application since the domains are different.
const cors = require('cors');
This lets you allow any frontend domain
app.use(cors({
origin: '*'
}));
This lets you allow certain ones
app.use(cors({
origin: ['https://siteA.com', 'https://siteB.com']
}));