0

I believe most of my response headers to be correct, but I still am unsure whether I have a concrete understanding of CORS. The error that the client gives seems to ignore the obvious 'Access-Control-Allow-Origin' header in the server. I wrote an OPTIONS request handler in the server code and put the headers in there after some research, which seemed to fix the problem except the GET handler doesn't execute so it didn't really fix anything.

Client error:

Access to XMLHttpRequest at 'http://localhost:8008/' from origin 'http://localhost:8000' 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.

GET http://localhost:8008/ net::ERR_FAILED

Client code:

const XML = new XMLHttpRequest()
XML.open("GET", "http://localhost:8008")
XML.setRequestHeader('Content-Type', "application/json")
XML.send({
    "hihihi":"hihihi"
})
// I've actually been doing this all in the console, so sorry if it looks messy

Server code:

const sqlite = require("sqlite3")

const express = require("express")
const parser = require("body-parser")

let maxID = 0

const database = new sqlite.Database("main")
database.run("CREATE TABLE main(Identifier INT NOT NULL, PlaybackStatus VARCHAR(255))")

const app = express()
app.use(parser.json())

app.options("/", (req, res) => {
    res.set('Access-Control-Allow-Origin', "http://localhost:8000")
    res.set('Access-Control-Allow-Methods', "GET")
    res.set('Access-Control-Allow-Headers', "Content-Type")

    console.log(`options: ${req.body}`)
})

app.get("/", (req, res) => {
    res.set('Access-Control-Allow-Origin', "http://localhost:8000")
    res.set('Access-Control-Allow-Methods', "GET")
    res.set('Access-Control-Allow-Headers', "Content-Type")

    res.set('Content-Type', "application/json")

    console.log(req.body)

    /*if (req.body.id == undefined && req.body.request != "Identifier") {
        res.send(JSON.stringify({
            code: 400,
            message: "Expected identifier"
        }))
    } else*/ if (req.body.request == "Identifier") {
        maxID++

        database.run(`INSERT INTO main (${maxID}, NULL)`)
        res.send(JSON.stringify({
            code: 200,
            data: maxID
        }))
    } else if (req.body.request == "PlaybackStatus") {
        database.get(`SELECT PlaybackStatus FROM main WHERE Identifier=${req.body.id}`, (row) => {
            res.send(JSON.stringify({
                code: 200,
                data: row
            }))
        })
    }
})

app.listen(8008, () => console.log("Listening on port 8008"))

Any and all help would be appreciated!

ph3b3
  • 1
  • 7
  • Did you try this answer? https://stackoverflow.com/a/21622564/7026966 Express doc on cors: https://expressjs.com/en/resources/middleware/cors.html – Himanshu Shekhar Jan 24 '23 at 08:57
  • GET requests have no body and therefore need no `Content-Type` header. And your `app.options` middleware lacks a `res.end()`, it will therefore never send a response. – Heiko Theißen Jan 24 '23 at 16:09
  • @HeikoTheißen isn't `res.send()` the same as `res.write(); res.end()`? – ph3b3 Jan 24 '23 at 23:02
  • @HeikoTheißen sorry, i misunderstood you. thanks, you helped a lot :) – ph3b3 Jan 24 '23 at 23:12

0 Answers0