#Access to fetch localhost:8000/api/graphql has been blocked due to CORS

10 messages · Page 1 of 1 (latest)

rare anchor
#

I'm using the CMS template and am now trying out the corresponding front end and it hits the following issue:

host:8000/api/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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. index.tsx:75

I have a general understanding of CORS but am curious of the best path forward within Payload to make this work. TIA.

tall tundra
#

Have you installed CORS and added it as a middleware in your server.js/server.ts?

rare anchor
#

@tall tundra no I haven't, do you have any recommendations on how to do this?

tall tundra
#

Here's an example of what my server.js looks like

#
const payload = require('payload');
const cors = require('cors')
const router = express.Router();
const app = express();
require('dotenv').config();

// Redirect root to Admin panel
app.get('/', (_, res) => {
  res.redirect('/admin');
});

//middleware
app.use('/api', router)
app.use(cors())
app.use(express.urlencoded({extended: true}))
app.use(express.json())

// Initialize Payload
payload.init({
  secret: process.env.PAYLOAD_SECRET,
  mongoURL: process.env.MONGODB_URI,
  express: app,
  onInit: () => {
    payload.logger.info(`Payload Admin URL: ${payload.getAdminURL()}`);
  },
});

// Add your own express routes here

app.listen(process.env.PORT);
iron burrow
#

@rare anchor Have you got something like this in your payload.config.ts

        'http://localhost:3000',
        PAYLOAD_PUBLIC_APP_URL,
    ].filter(Boolean), 
full ridge
charred wyvern
#

@full ridge I'm a year late to the party and using V3 but I'm running into this issue with custom endpoints on collections. cors and csrf are set up in the config as per the documentation but the only way I've got a custom endpoint to work is by adding custom cors headers to the custom endpoint response, which doesn't seem ideal. I know the docs say you're responsible for securing your own endpoints, but what does that actually mean?