Home > Mobile >  I have problems with Post method in my CORS?
I have problems with Post method in my CORS?

Time:02-06

I am developing an app with my own sever, i configured my cors with to by client-side host only. Everything seems to be fine i can request data from my database using the GET, but whenever my trying to POST or create, I always have "Response to preflight request doesn't pass access control check:". Please what am I doing wrong? Below is my code

My server-side

const allowedOrigins = [
    'http://localhost:3000/'
]
const CorsOptions = {
    origin: allowedOrigins,
    Credentials: true,
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
    allowedHeaders: ['Content-Type'],
    optionsSuccessStatus: 204
}
const cors = require('cors')
const CorsOptions = require('./config/CorsOptions')
app.use(cors(CorsOptions))
app.use(express.urlencoded({ extended: false }))
app.use(express.json())

My client-side

  const response = await fetch('http://localhost:8000/workout', {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {
                'Content-Type':'application/json'
            },
        })
        const json = await response.json()
        if(!response.ok){
            errors(json.message)
        }
        if(response.ok){
            reset(data)
            console.log('New Workout added successfully', json)
        }

The error

Access to fetch at 'http://localhost:8000/workout' 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.

The GET request works perfectly with all these setting above, but for some reason the POST or any other request always gives me this error

I havent done anything yet, i would appreciate any help.

CodePudding user response:

Most likely a permissions issue,

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "http://localhost:3000");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

Configuring CORS headers into server-side code to allow requests from the local host

This header specifies which domains are allowed to make requests to your server.

CodePudding user response:

If you're using Chrome to debug your application, then that could be why, since Chrome doesn't support making POST requests from localhost. A bug report was made for this, but it was marked as WontFix, so it's likely not going to change any time soon.

This extension circumvents the issue by setting the Access-Control-Allow-Origin header to *, along with some other stuff.

You may also want to consider this npm package, since you're already using Express.

Hope this helps!

  • Related