I am trying to access an api i built using express.js and am hosting on dreamhost but whenever i try to access it from another domain I run into CORS issues: "has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."
I have tried using app.use(cors()) to no avail. I've even edited the .htaccess file.
When I check to see the headers that are being returned from my api, there are no lines showing the Access-Control-Allow-Origin information.
Code for express app:
const express = require('express');
const homeRouter= require('./routes/home.js');
const pmonboardingRouter= require('./routes/pmonboarding.js');
const resourceRouter= require('./routes/resource.js');
const userRouter= require('./routes/user.js');
const cors =require('cors');
// import helmet from 'helmet';
const app = express();
// app.use(helmet());
const port= process.env.SERVER_PORT || 3001;
app.use(express.json());
app.use(express.urlencoded({extended:true}))
app.use(cors({ origin: true }));
app.use('/resources',resourceRouter);
app.use('/pmonboarding',pmonboardingRouter);
app.use('/user',userRouter);
app.use('/',homeRouter);
Code for .htaccess file:
Header add Access-Control-Allow-Origin: "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header add Access-Control-Allow-Headers: "Content-Type"
Code for front end access:
fetch('<My api Domain>', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
Any help would be much appreciated! Thanks.
CodePudding user response:
I Dont think So, Error looks 301. Can you try once with postman directly api.
Below one for reference for CROS issue,
const cors = require('cors');
app.use(cors({
origin: 'https://www.domain.io'
}));
//or
app.use(cors({
origin: ['https://www.domain.io', 'https://www.google.com/']
}));
//or
app.use(cors({
origin: '*'
}));
//for origin with methods
app.use(cors({
methods: ['GET','POST','DELETE','UPDATE','PUT','PATCH'],
origin: '*'
}));
// maybe like this
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
CodePudding user response:
Sometimes it occurs because of calling method just check once that what method you are using in api side get/post/put/delete