Skip to content

how to make a post request to create new users in react-chat-engine

I’m creating a chat app with react-chat-engine. and everything is working fine. except for the fact that I don’t know how to make a post request to create new users. Please can anyone help me out. I really need this.

Here’s my code

const handelSubmit = async(e) => {
  e.preventDefault();
  if (!(username.length > 0 && password === confirmPassword && password.length > 0)) return;

  const authObject = {
    'Private-Key': '2f389292-d5e1-4799-bd31-b456e7e94845',
    // 'Project-ID': '25a91c10-8623-4a0d-a48a-3de096d44b54',
    // 'User-Name': username,
    // 'User-Secret': password
  }

  const authHeader = {
    'Private-Key': '2f389292-d5e1-4799-bd31-b456e7e94845',
    'Project-ID': '25a91c10-8623-4a0d-a48a-3de096d44b54',
  }
  // const authBody = {
  //    'username': username,
  //    'secret': password
  // }



  try {
    //fetch the current user if it exists
    const userExists = await axios.get('https://api.chatengine.io/users', {
      headers: authObject
    });
    console.log('worked');
    console.log(userExists);
    // if user already exists and in localStorage redirect them to the chat room
    if (userExists && (localStorage.getItem('username') && localStorage.getItem('username') === username)) {
      setTimeout(() => {
        history.push('/chat')
      }, 1000)
      return;
    }
    console.log('worked2');
    // if user don't exists, create a new user 
    await axios.post('https://api.chatengine.io/users', {
      headers: authHeader,
      body: {
        'username': username,
        'secret': password
      }
    });
    // //saving user's username and password to localStorage
    // localStorage.setItem('username', username);
    // localStorage.setItem('password', password);
    //redirecting them to the login page to login
    console.log('worked25');
    history.push('/login')
  } catch (error) {
    console.log(error);
    setError(`oops, something went wrong`)
  }

}

Please. ignore other lines and focus on the try/catch path I’m trying to add a new user to the users. But it keeps throwing this error to the console.

Error: Request failed with status code 403
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

What can I do

Answer

Try making

const authHeader = {'Private-Key': '2f389292-d5e1-4799-bd31-b456e7e94845'}

only and adding a / to the end in https://api.chatengine.io/users/ and I think it will work

If not, then your private key is probably incorrect.

(Also you should not be posting your private key online like this, it’s private for a reason.)