Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

cookies - req.session with different domains node.js

I'm building an app using next.js and node.js (express).

The client run on localhost:4000, and the server run on lovalhost:3000.

to communicate between the two domains Iwm using cors().

to authorization i'm using with cookieSession and jwt.

app.use(
  cookieSession({
    signed: false,
    secure: false,
    sameSite: false,
  })
);

when user login i put on the session a jwt.

 req.session = {

jwt:userJwt };

this time the user needs to be identified by the cookie.

this works nice in postman environment, when a user sign in he is identified, the cookie with his jwt is saved. but when i try to make the same request via the client unforteantually the cookie is not saved.

the client code:

   const signin= () => {
   const [email, setEmail] = useState('');
   const [password, setPassword] = useState('');

   const {doRequest, errors} = useRequest({
    url: 'http://localhost:4000/api/auth/signin',
    method: 'post',
    body: {
    email,password
   },
   onSuccess: () => Router.push('/')
  });

the useRequest hook:

import axios from 'axios';
import { useState }  from 'react';

const useRequest= ({url, method, body, onSuccess}) => {
const [errors, setErrors] = useState(null);
const doRequest =async () => {
try {
  setErrors(null);
  console.log(url);

  const response = await axios[method](url,body);
  console.log(response);
  
  if(onSuccess) {
   onSuccess(response.data);
  }
  
   return response.data;
 } catch (error) {
   console.log(error);
   setErrors(
    <div className= "alert alert-danger" >
       <h4>Ooops...</h4>
       {error.response.data ?
       <ul className="my-0">
         {error.response.data.errors.map(err => (
          <li key = {err.message}> {err.message}</li>
        ))}
     </ul>:{}
  }
   </div>
   );
  }
 };

return { doRequest,errors }
};

export default useRequest;

Maybe because the diffrent domains the session is not the same?

How can I slove it?

My app

I hope I was clearly.

thank you!

I'm using process.env variables

question from:https://stackoverflow.com/questions/65862712/req-session-with-different-domains-node-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...