I have node js server which you can view here - https://github.com/Inibua/ServerNodeJS
In index.js
I have the following
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const passport = require('passport')
const localSignupStrategy = require('./passport/local-signup')
const localLoginStrategy = require('./passport/local-login')
const authRoutes = require('./routes/auth')
const postRoutes = require('./routes/post')
const commentRoutes = require('./routes/comment')
const app = express()
const port = 5000
const envConfig = require('./config/environment')
require('./config/database')(envConfig)
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://roomy-hook.surge.sh');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(passport.initialize())
//app.use(cors())
passport.use('local-signup', localSignupStrategy)
passport.use('local-login', localLoginStrategy)
// routes
app.use('/auth', authRoutes)
app.use('/post', postRoutes)
app.use('/comment', commentRoutes)
app.listen(port, () => {
console.log(`Server running on port ${port}...`)
})
the app.use()
which addes Access-Control-Allow-Origin
is copied from here - No 'Access-Control-Allow-Origin' - Node / Apache Port Issue
I have also tried the other questions as well, but it doesn't work.
I have tried
app.use(cors())
app.use(cors({origin:"front-end-url"}))
app.use(cors({origin:null}))
app.use(cors({origin:"*"}))
as stated in other answers, but nothing works.
Here is the error I get -
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If you want to recreate it here is the url for the front-end http://roomy-hook.surge.sh Here you need to first press Login
and fill the form and press "Sign up" on the console you will see the error.
If needed here is the route for login and
signupinside
routes/auth.js`
const express = require('express')
const passport = require('passport')
const validator = require('validator')
const userController = require('../controllers/user')
const router = new express.Router()
function validateSignupForm (payload) {
const errors = {}
let isFormValid = true
let message = ''
if (!payload || typeof payload.password !== 'string' || payload.password.trim().length < 4) {
isFormValid = false
errors.password = 'Password must have at least 4 characters.'
}
if (!payload || typeof payload.username !== 'string' || payload.username.trim().length === 0) {
isFormValid = false
errors.name = 'Please provide your name.'
}
if (!isFormValid) {
message = 'Check the form for errors.'
}
return {
success: isFormValid,
message,
errors
}
}
function validateLoginForm (payload) {
const errors = {}
let isFormValid = true
let message = ''
if (!payload || typeof payload.password !== 'string' || payload.password.trim().length === 0) {
isFormValid = false
errors.password = 'Please provide your password.'
}
if (!isFormValid) {
message = 'Check the form for errors.'
}
return {
success: isFormValid,
message,
errors
}
}
router.post('/signup', (req, res, next) => {
const validationResult = validateSignupForm(req.body)
if (!validationResult.success) {
return res.status(200).json({
success: false,
message: validationResult.message,
errors: validationResult.errors
})
}
return passport.authenticate('local-signup', (err, user) => {
if (err) {
return res.status(200).json({
success: false,
message: err
})
}
return res.status(200).json({
success: true,
user: req.body,
message: 'You have successfully signed up! Now you should be able to log in.'
})
})(req, res, next)
})
router.post('/login', (req, res, next) => {
const validationResult = validateLoginForm(req.body)
if (!validationResult.success) {
return res.status(200).json({
success: false,
message: validationResult.message,
errors: validationResult.errors
})
}
return passport.authenticate('local-login', (err, token, userData) => {
if (err) {
if (err.name === 'IncorrectCredentialsError') {
return res.status(200).json({
success: false,
message: err.message
})
}
return res.status(200).json({
success: false,
message: 'Could not process the form.'
})
}
return res.json({
success: true,
message: 'You have successfully logged in!',
token,
user: userData
})
})(req, res, next)
})
module.exports = router