I wrote a rest api to handle all requests for my chat app, such as logging in, signing up, or sending a message. This works fine for my serverside code;however, I want logging in or signing up to send a request to the rest api instead. On the api, the request is never received from the client. I tried testing it basically in a similar way on a separate directly
I'm working on a chat app I started around a month ago
Code for server that handles logins:
app.route('/login').post(async (req, res) => {
console.log('login request')
var users = await serverController.listDocuments({
database:'chatbase',
collectionName:'users',
query:`{'username':'${req.body.usrnm}'}`
})
if(!users[0]) return res.send('Incorrect Credentials')
var user = new User(users[0])
var isCorrect = await bcrypt.compare(req.body.psw, user.password)
if(!isCorrect) return res.send('Incorrect Credentials')
res.send({token: user.token, username:user.username, id:user.id})
})
Code for client side:
let xhr = new XMLHttpRequest()
xhr.open("POST", 'https://api.domain.com')
xhr.setRequestHeader('Content-Type', "application/json");
xhr.onreadystatechange = () => {
if (xhr.status == 200) {
alert('Reqest succeeded');
}
alert(xhr.status)
}
xhr.send(JSON.stringify({
usrnm:'Example Username',
psw:'Example Password'
}))
Code for server(Works):
socket.on('login', credentials => {
var opt = {
uri:'https://message-api.glitch.me/login',
method:'POST',
body:credentials,
headers: {
'User-Agent': 'Request-Promise'
},
json:true
}
rp(opt)
.then(res => {
if(res == 'Incorrect Credentials') return socket.emit('loginFailed')
socket.emit('loginSuccess', res)
})
})
The serverside code receives creds from user and then forwards them to api. The server then receives either a token that the user can send messages using or it sends an incorrect login(Works). The api code simply routes various request types, such as creating servers or logging in(Works from serverside requests). The client side creates a reqyest and then sends it(Is never recieved)