Django中的登录方法可以很好地与POSTMAN配合使用,但与前端配合使用时,除了登录方法外,其他一切都可以



我是React Js的新手,想将我的React应用程序与Django连接起来。我创建了CustomUser用于身份验证,login((用于会话,并使用rest_framework.auth.Token(Token(用于登录。现在,当我通过POSTMAN发送POST请求时,会正确创建会话并返回电子邮件和身份验证令牌,但当我使用React Js(前端(发送POST请求时一切正常(返回电子邮件和令牌(,但登录方法不会创建会话,因此user.is_authenticated返回False。如何解决这个问题。提前感谢。

我的视图.py

@csrf_exempt
def signin(request):
if request.method == 'GET':
if request.user.is_authenticated:
token,created = Token.objects.get_or_create(user=request.user)

return JsonResponse({"Email":request.user.email,"Auth-token":token.key},safe=False)
return render(request,'application/signup.html')
if request.method == 'POST':
# if not request.user.is_authenticated:
data = JSONParser().parse(request)
email = data['email']
print(email)
b1 = email.replace("@","")
password = data['password']
print(password)
user = authenticate(request,email=email,password=password)
if user:
location = str(pathlib.Path().absolute())+'CameraDatabaseImageDatabaseImage\' + b1 + '.jpg'
print(location)
answer = facedect(location)
if answer=="Retry":
messages.error(request,"Captured Image is not clear Please be in light")
#React
#return render(request,"application/signup.html")
return JsonResponse("Captured Image is not clear Please be in light",safe=False)
if answer == True:
login(request,user)
token,created = Token.objects.get_or_create(user=request.user)
messages.success(request,"Account created")
#React 
#return redirect('http://localhost:8000/homepage/')
return JsonResponse({"Email":request.user.email,"Auth-token":token.key,"answer":"abhi login hua hai"},safe=False)
else:
print("Face Not Found")
messages.error(request,"Face Not Found")
#React
#return render(request, 'Facebook.html')
return JsonResponse("Face Not Found",safe=False)
messages.error(request,"Invalid Email or Password")
#React
# return render(request,"application/signup.html")
return JsonResponse("Not a Valid Email Address Or Password",safe=False)

myReact.js代码

import { Redirect } from "react-router";
import "../Css/Navbar.css";
class Navbar extends Component{
constructor(props){
super(props)
this.state={
email:'',
password:''
};
}
credential=(e)=>{
let name = e.target.name
let value = e.target.value
this.setState({[name]:value})
}
login = (e)=>{
let data1;
e.preventDefault()
console.log(this.state.email);
console.log(this.state.password);
fetch("http://localhost:8000/login/",{
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify(this.state)
}).then(data=>data.json()).then(data=>{
data1 = data
return console.log(data)}).catch(error=>console.log(error))

}

render(){
return(
<>       
<nav className="navbar navbar-expand-lg navbar-dark bg-dark px3 py3 mt1">
<a className="navbar-brand font-weight-bold"  >facebook</a>

<form className="ml-auto">
<div className="form-row">
<div className="col">
<input type="email" name="email" className="form-control form-control-sm mr-2" value={this.state.email} onChange={this.credential} placeholder="Email" />
</div>
<div className="col">
<input type="password" name="password" className="form-control form-control-sm mr-2" value={this.state.password} onChange={this.credential} placeholder="Password" />
</div>
<button type="submit" className="btn btn-primary btn-sm " onClick={this.login}>Login</button>
</div>
</form> 
</nav>


</>
);
}}
export default Navbar;

默认情况下,跨源请求不会随请求一起发送凭据(cookie、cookie、HTTP身份验证条目和TLS客户端证书(。服务器确实在用户会话中设置了一些变量,但当您向服务器发出后续请求时,这些变量永远不会被使用。要使用凭据向服务器发出请求,您需要在fetch的init选项上设置credentials: 'include'(对向服务器发出的所有请求都要这样做(。因此,您的fetch呼叫应该是:

fetch("http://localhost:8000/login/",{
credentials: 'include'
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify(this.state)
})

参考:发送一个包含凭据的请求[developer.mozilla.org/

最新更新