gpt4 book ai didi

reactjs - 错误 : A cross-origin error was thrown. 错误:应该设置一个 secret

转载 作者:行者123 更新时间:2023-12-03 17:11:58 27 4
gpt4 key购买 nike

我正在学习制作电子商务网站的类(class),当我尝试注册用户时,我收到此错误:
enter image description here
讲师克隆了我的存储库并没有收到任何错误,但是每当我尝试注册或登录时都会收到错误消息。
我该如何解决这个问题?任何帮助将非常感激。
也许我用来处理错误的 errorHandler 文件存在问题。
Controller /auth.js

const User = require('../models/user')
const jwt = require('jsonwebtoken') // to generate signed token
const expressJwt = require('express-jwt') // for authorization check
const { errorHandler } = require('../helpers/dbErrorHandler')

exports.signup = (req, res) => {
console.log("req.body", req.body)
// signs up new user
const user = new User(req.body)
user.save((err, user) => {
if(err) {
return res.status(400).json({
err: errorHandler(err)
})
}
user.salt = undefined
user.hashed_password = undefined

res.json({
user
})
})
}

exports.signin = (req, res) => {
// find user based on email
const { email, password } = req.body
User.findOne({email}, (err, user) => {
if (err || !user) {
return res.status(400).json({
error: 'User with that email does not exist.'
})
}
// if user is found, ensure email & password match
// create authenticate method in user model
if (!user.authenticate(password)) {
return res.status(401).json({
error: 'Email and password dont match'
})
}
// generate signed token with user id and secret
const token = jwt.sign({_id: user._id}, process.env.JWT_SECRET)

// persist token as 't' in cookie with expiry date
res.cookie('t', token, {expire: new Date() + 9999 })

// return response with user & token to frontend client
const {_id, name, email, role} = user
return res.json({token, user: {_id, email, name, role}})
})
}

exports.signout = (req, res) => {
res.clearCookie('t')
res.json({ message: "Signout success" })
}

exports.requireSignin = expressJwt({
secret: process.env.JWT_SECRET,
userProperty: 'auth'
})

exports.isAuth = (req, res, next) => {
let user = req.profile && req.auth && req.profile._id == req.auth._id
if(!user) {
return res.status(403).json({
error: "Access denied"
})
}
next()
}

exports.isAdmin = (req, res, next) => {
if (req.profile.role === 0) {
return res.status(403).json({
error: 'Admin resource! Access denied'
})
}
next()
}

控制台中的错误消息:
  throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
^
Error [MongooseError]: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.

最佳答案

您在组件中存在未捕获的异常 Signup Signin .

// Signin.js
const clickSubmit = (event) => {
event.preventDefault()
setValues({ ...values, error: false, loading: true })
signin({ email, password }).then(data => {
if (data.error) {
setValues({ ...values, error: data.error, loading: false })
} else {
authenticate(data, () => {
setValues({
...values,
redirectToReferrer: true
})
})
}
}).catch(exc => {
console.error("+++ exc signin: ", exc)
// we log error
setValues({ ...values, error: exc.message, loading: false })
});
}



// Signup.js
const clickSubmit = event => {
event.preventDefault();
setValues({ ...values, error: false });
signup({ name, email, password }).then(data => {
console.log("++ data: ", data);

// if you need to check error from backend
// else all exceptions are captured in catch block
if (data.error) {
setValues({ ...values, error: data.error, success: false });
} else {
setValues({
...values,
name: '',
email: '',
password: '',
error: '',
success: true
});
}
}).catch(exc => {
console.error('++ exc: ', exc);

setValues({ ...values, error: exc.message, success: false });
})
};
然后在 auth/index.js , 只返回 fetch promise 并让调用函数处理异常。
 // cors mode to allow cross-origin 
export const signup = (user) => {
return fetch(`${API}/signup`, {
method: "POST",
mode: 'cors',
headers: {
Accept: 'application/json',
"Content-Type": "application/json"
},
body: JSON.stringify(user)
})
.then(response => {
return response.json()
})

};



// mode cors to allow cross-origin access
export const signin = (user) => {
return fetch(`${API}/signin`, {
method: "POST",
mode: 'cors',
headers: {
Accept: 'application/json',
"Content-Type": "application/json"
},
body: JSON.stringify(user)
})
.then(response => {
return response.json()
})

}
在后端,请确保设置了这些键 process.env.JWT_SECRET 或者您可以使用默认值以防未设置键或在未设置重要键时在启动时退出应用程序。
process.env.JWT_SECRET || 'default_ket'
您需要在 ecommerce-back 的根目录中创建 .env 文件
DATABASE=mongodb://localhost:27017/Ecommerce
JWT_SECRET=secret
在这里,Mongo 在默认端口上运行,您的数据库名称是 Ecommerce,否则根据您的设置设置值。

关于reactjs - 错误 : A cross-origin error was thrown. 错误:应该设置一个 secret ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61952936/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com