I was testing get and post requests in jsfiddle to better understand cors and csrf.
const data = { name: 'example', password: 'password'};
fetch('http://localhost:3001', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hi')
})
app.post('/', (req, res) => {
console.log('received')
res.send('Received')
})
app.listen(3001, () => {
console.log('Listening on port', 3001)
})
Is it normal that the first preflight request fails when doing a post request?
Also, shouldn't the successful preflight request happen before the post request? (On the server side, the code handling the post request isn't executed (nothing logged in console), which means that the browser cancelled the post request. How would the browser know not to follow through with the post request without waiting for the preflight request to complete first?)
Update: Tried it using a simple html page instead of jsfiddle and the preflight request doesn't fail, but it still happens after the fetch request
Edit: Only one options request is received on the server
// debugging middleware, should be first router handler of any kind
let requestCntr = 0
app.use((req, res, next) => {
let thisRequest = requestCntr
console.log(
`${thisRequest}: ${req.method}, ${req.originalUrl}, `,
req.headers
)
// watch for end of theresponse
res.on('close', () => {
console.log(
`${thisRequest}: close response, res.statusCode = ${res.statusCode}, outbound headers: `,
res.getHeaders()
)
})
next()
})
Edit 2: from console For a get request, no network error is shown in the Network tab, but the same error appears in the console except with a status code
CodePudding user response:
It seems that Chrome simply displays the preflight request with a network error in the Network tab if it's related to csrf. Since opaque GET requests are fine, this doesn't happen for GET requests. So in the case of a post request, even if "preflight" shows up twice, it's the same preflight request.