0

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 andsignupinsideroutes/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
Pavlin Petkov
  • 1,022
  • 3
  • 17
  • 38
  • Did you change something to the server? I just tried sign-up and it's giving `404 Not Found` instead of No Access Control Allow – Raul Rene Dec 22 '17 at 12:48
  • I try debugging it and sometimes I stop the server and rerun it. I just tried it and it gives the correct error. here is a screenshot http://prntscr.com/hqzd31 – Pavlin Petkov Dec 22 '17 at 12:51
  • There might be something fishy with how the header handles your direct link to the site. Just try setting `res.header("Access-Control-Allow-Origin", "*");` instead of `res.setHeader('Access-Control-Allow-Origin', 'http://roomy-hook.surge.sh');` to check if it works for `*` – Raul Rene Dec 22 '17 at 12:53
  • Is there a reason you are using `res.header` instead of `res.setHeader` or is it a typo? In other answers it is with `res.setHeader` – Pavlin Petkov Dec 22 '17 at 12:56
  • It works either way. Also, if that doesn't work, add the allowed `Origin` header in the allow-headers: `res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With,content-type')`; – Raul Rene Dec 22 '17 at 12:58
  • On the server I have added the first response with the change to allow every url with `*` but it still doesn't work – Pavlin Petkov Dec 22 '17 at 13:02
  • I have also added the code from the answer inside `routes/auth.js` and it still doesn't work – Pavlin Petkov Dec 22 '17 at 13:09
  • Луцка you are forgetting the port `http://164.138.216.49` this address is pointing to IIS server and I guess your nodejs server is not running there. Try `http://164.138.216.49:nodejs_port/auth/login` where nodejs_port is the port on which your nodejs server is running – codtex Dec 22 '17 at 13:34
  • @codtex The port is 6969 and when I add the port into the request I get 502 Bad Gateway as well as missing Allow Access Control Origin error. – Pavlin Petkov Dec 22 '17 at 17:05
  • Луци this could be a variety of reasons. What I was going to do is setup a basic nodejs server with a sample `GET` path e.g. `http://164.138.216.49:6969/test` that simply returns `Hello world` and once I see the message, proceed with the complicated logic. The 502 error could be coming from the server configuration itself or IIS – codtex Dec 22 '17 at 17:26
  • @codtex I have a very basic route which is `/post/all` which is simple GET request which returns objects from the database. The problem is that it doesnt reach the `route`. Sadly I have no control over the server on which my app is hosted. I have messaged the support of my hosting provider to provide me with useful link, if he doesnt - Despite this I have no idea how I could change my code to work. There doesnt seem to be any error in the code. I have checked every similar question and tried every possible option. – Pavlin Petkov Dec 22 '17 at 17:30

1 Answers1

1

add cors in option in every url.

var cors = require('cors');    
router.options('/post', cors());
router.post('/post');
zabusa
  • 2,520
  • 21
  • 25
  • Where should I add this? In index.js I am not using router.options but I use it in `router/auth.js` – Pavlin Petkov Dec 22 '17 at 12:52
  • @ЛуциПетков add it in the above of every urls in the routes folder you need cors.if you are using the cors no need to put the extra cors object in app.use. – zabusa Dec 22 '17 at 12:54
  • I added it to the server in `routes/auth.js` for routes `signup` and `login` and it still gives the same error – Pavlin Petkov Dec 22 '17 at 13:08