-3

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?

network console

cors error

failed preflight

successful preflight

successful preflight

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

enter image description here

enter image description here

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()
})

enter image description here

Edit 2: from console enter image description here 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 enter image description here

enter image description here

enter image description here

  • Related/similar to earlier questions [here](https://stackoverflow.com/questions/74935892/where-are-options-requests-handled-in-express) and [here](https://stackoverflow.com/questions/74933041/understanding-preflight-requests) and [here](https://stackoverflow.com/questions/74931029/csrf-and-cors-why-allow-the-request-to-happen-if-we-know-there-will-be-a-cors-e). – jfriend00 Dec 28 '22 at 23:06
  • 1
    I think you should see the answer to your [earlier question](https://stackoverflow.com/questions/74935892/where-are-options-requests-handled-in-express/74946262#74946262) and see if it also provides enough info to explain this one. – jfriend00 Dec 29 '22 at 01:00
  • Thank you, it does explain why the order in the console is misleading, but I am still confused by why there is a network error on the preflight request when doing a post request (doesn't happen for a get request). It seems to be [related to cors](https://stackoverflow.com/questions/22665232/what-can-cause-chrome-to-give-an-neterr-failed-on-cached-content-against-a-ser), but I can't piece it together. – Dropin' Science Dec 29 '22 at 06:48
  • What network error? Are you getting an http status code back or truly getting a network error where the `fetch()` rejects? What is the EXACT output you get from your `fetch()` call? It wouldn't surprise me if a CORs error comes back to `fetch()` as a network error (the request was denied). – jfriend00 Dec 29 '22 at 09:25
  • When I click on the first preflight request in the chrome console to highlight it, it says "(failed) net:ERR_FAILED". That preflight request doesn't reach the server. The fetch request indeed has a cors error. – Dropin' Science Dec 29 '22 at 16:25
  • I repeat, ***What is the EXACT output you get from your fetch() call*** in your Javascript code? What specific error do you get? Do you get a network error there?If so, what exactly is it? You are over relying on the inspector and the debug output there (as you were in the previous question too). You need to study the two endpoints and see what is really happening on each end. – jfriend00 Dec 29 '22 at 16:48
  • This is very difficult to get you to answer a simple question. I'm asking what the results of the `fetch()` call is in the client (3rd time I've asked). What does `.catch((error) => { console.error('Error:', error); });` from the `fetch()` call show? You're pretending to see and understand errors in the inspector, but that isn't the actual story. That's just some debug log, not the ACTUAL error that comes back from the `fetch()` call. That's what I want to know. – jfriend00 Dec 29 '22 at 19:48
  • FYI, I've already explained in the other answer that the prefetch returns successfully (due to a default handler in Express), but WHAT it returns is a set of what is allowed and it does NOT allow `application/json` as a content-type. The browser sees that your POST request is `content-type: application/json` so it is disallowed by the browser as a CORS violation since that content-type is not allowed for CORS requests by default. – jfriend00 Dec 29 '22 at 19:51

1 Answers1

0

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.