admin管理员组文章数量:1122846
Hello and good morning from Nigeria... I have the following CORS error in Firefox: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3001/socket.io/?EIO=4&transport=polling&t=PGwfo3y. (Reason: CORS request did not succeed). Status code: (null).
Network panel: request headers
I am using a wrapper around Express to bootstrap my backend.
You can find the code at: .js
Here's a copy to avoid redundancy:
import express from 'express'
import Router from './Router.js'
import Model from './Model.js'
import getResponse from '../helpers/responseHelper.js'
import mongoose from "mongoose"
import cors from 'cors'
import helmet from 'helmet'
import index from '../routes/index.js'
import token from '../routes/token.js'
import auth from './../middlewares/auth.js'
import packageJson from './../package.json' assert { type: "json" }
import crypto from 'crypto'
/**
* Kratos class
*/
export default class Kratos {
#app = express()
#consoleColor = '\x1b[36m%s\x1b[0m'
#localConfig = {
port: this.#generatePort(),
api_version: 1,
version: packageJson.version
}
constructor(config) {
/**
* Initialize a new Kratos instance.
*
* @param config The default config for Kratos initialization
*/
this.config = config
this.port = parseInt(this.config.port)
this.api_version = (this.config.version) ? this.#getMajorVersion(this.config.version) : this.#localConfig.api_version
this.baseURL = `/api/v${this.api_version}`
this.db_server = this.config.db_server
this.disable_auth = (this.config.disable_auth) ? this.config.disable_auth : false
this.version = 'Kratos version: ' + this.#localConfig.version
this.maintenance = (this.config.maintenance) ? this.config.maintenance : false
this.cors_origins = (this.config.cors_origins) ? this.config.cors_origins : []
this.show_secret = (this.config.show_secret) ? this.config.show_secret : false
this.jwt_secret = (this.config.jwt_secret) ? this.config.jwt_secret : crypto.randomBytes(32).toString('hex')
this.unprotected_routes = (this.config.unprotected_routes) ? this.config.unprotected_routes : []
}
/**
* Serve the Kratos application
*
* @param {Object} defaultRouter Default router object
* @param {Object} customRouter Custom router object (optional)
*/
launch(defaultRouter, customRouter) {
// Initialize middlewares
this.#initMiddlewares(this.#app)
// Initialize config
this.#initConfig(this.#app)
// Initialize routers
this.#initRoutes(this.#app, defaultRouter, customRouter)
// Initialize DB
this.#initDB(this.#app)
.then(() => {
this.#app.listen(this.port, () => console.log(`Kratos app is running on port: ${this.port}`))
})
}
/**
* Return JSON HTTP Response
*
* @param {Number} statusCode Status code
* @param {Response} res Resource response object
* @param {Object} data Data object to respond with in case of successful response
*/
respond(statusCode, res, data) {
return getResponse(statusCode, res, data)
}
/**
* Initialize new Router
*
* @param {Object} resources resources object
*/
router(resources) {
return new Router(resources)
}
/**
* Initialize new Model
*
* @param {String} name Model name
* @param {Object} resource Resource object
* @param {Request} req Resource request
*/
model(name, resource, req) {
return new Model(name, resource, req)
}
/**
* Wrapper for express.Router()
*
* @param {Object} options Router options
*/
expressRouter(options) {
return express.Router(options)
}
/**
* Return current endpoint from request (refactoring soon)
*
* @param {Object} req Request object
*/
getEndpoint(req) {
const urlString = req.baseUrl
const urlPaths = urlString.split('/')
return urlPaths[4].toLowerCase()
}
// Generates port for server to listen on
#generatePort() {
return Math.floor(Math.random() * 10000)
}
// Utility method to return major version
#getMajorVersion(version) {
const strings = version.split('.')
return strings[0]
}
// Initialize routes
#initRoutes(app, defaultRouter, customRouter) {
console.log(this.#consoleColor, 'Initializing routes...')
// Index route
app.use(`${this.baseURL}/`, index)
// JWT route
app.use(`${this.baseURL}/get-token`, (!this.disable_auth) ? token : (req, res) => {
return this.respond(404, res)
})
app.use(`${this.baseURL}/show-secret`, (this.show_secret) ? (req, res) => {
return this.respond(200, res, { jwt_secret: this.jwt_secret })
} : (req, res) => {
return this.respond(404, res)
})
// Custom routes
app.use(`${this.baseURL}/custom`, (customRouter) ? customRouter : (req, res) => {
return this.respond(404, res)
})
// Default routes
app.use(`${this.baseURL}/:resource`, defaultRouter)
}
// Initialize middlewares
#initMiddlewares(app) {
console.log(this.#consoleColor, 'Initializing middlewares...')
app.use(cors({
origin: this.cors_origins,
optionsSuccessStatus: 200
}))
app.use(express.json({ limit: '2mb' }))
app.use(express.urlencoded({ extended: true, limit: '2mb' }))
app.use(
helmet({
contentSecurityPolicy: false,
xDownloadOptions: false,
})
)
// Set necessary config items in req object
app.use((req, res, next) => {
req.jwt_secret = this.jwt_secret
req.baseUrl = this.baseURL
req.unprotected_routes = this.unprotected_routes
next()
})
// Report downtime if maintenance mode is turned on
app.use((req, res, next) => {
if (this.maintenance) {
return getResponse(503, res)
} else {
next()
}
})
// Decide which authentication middleware to use
if (!this.disable_auth) {
app.use(auth)
}
}
// Initialize database
async #initDB() {
console.log(this.#consoleColor, 'Initializing database connection...')
return await mongoose
.connect(this.db_server)
.then((response) => {
return response
})
.catch((err) => {
console.log(err)
})
}
// Initialize config
#initConfig(app) {
console.log(this.#consoleColor, 'Initializing config...')
app.keepAliveTimeout = (this.config.keepAliveTimeout) ? this.config.keepAliveTimeout : 120 * 1000
app.headersTimeout = (this.config.headersTimeout) ? this.config.headersTimeout : 120 * 1000
}
}
Please observe how I make use of the CORs package. It doesn't seem to work no matter what I do. Also no errors so it's pretty difficult figuring out what's wrong on my own.
Here's how I instantiate the class in my bootstrap project:
import Kratos from '@kratosbase/kratos'
import user from './resources/user.js'
import code from './resources/code.js'
import routes from './routes.js'
const app = new Kratos({
port: 9000,
db_server: 'mongodb://127.0.0.1:27017/prochess',
cors_origins: ['http://localhost:3000'],
jwt_secret: "547a187b49c973e87c27cabb34dd4c92f873dd47e1fb01a889bd8b9de5066094",
unprotected_routes: ['/custom/send-code', '/custom/verify-code']
})
const defaultRoutes = app.router({
users: user,
codes: code
}).getRoutes()
app.launch(defaultRoutes, routes)
You can fork the code and test locally and let me know what's up.
Cheers and happy new year.
I installed the CORS package and tried:
app.use(cors({
origin: this.cors_origins,
optionsSuccessStatus: 200
}))
app.use(cors({
origin: this.cors_origins, // Allow requests from your Nuxt app
methods: ['GET', 'POST'], // Allow specific HTTP methods
credentials: true, // Allow cookies and authorization headers
allowedHeaders: 'Content-Type, Authorization'
}))
Express seems to be ignoring the app.use for some reason... not sure why.
I noticed also that the CORs error still comes up even when the server is offline, could this be a frontend issue?
本文标签: nodejsCORS error only in FirefoxHow do I fix this in my Express backendStack Overflow
版权声明:本文标题:node.js - CORS error only in Firefox, How do I fix this in my Express backend? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736281723a1926409.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论