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!