Reputation: 125
I have a server.js file. With a post request (/login). It looks like this:
require('dotenv').config();
const express = require('express');
const mysql = require('mysql')
const app = express();
const PORT = process.env.PORT || 3000
app.listen(PORT, console.log(`Server started on port ${PORT}`))
app.post('/login', (req, res) => {
console.log("login")
console.log(req);
})
I also have a function in NativeScript that is supposed to make a post request (where the fetch is) when a button is pressed. It looks like this:
export function onLoginButtonTap() {
console.log("login button tapped")
const frame = Frame.getFrameById("mainFrame");
// TODO: user authentication
var userEmail = `${bindingContext.get('email')}`;
var userPassword = `${bindingContext.get('password')}`;
// make sure fields are filled out
if (userPassword === "" || userEmail === "") {
alert({
title: "Login Error",
message: "One or more fields is empty. Please fill in every field.",
okButtonText: "OK",
})
} else {
// TODO: post request (send user input to backend for verification)
console.log("here1")
const data = {userEmail, userPassword};
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}
fetch("http://localhost:3000/login", options);
// if user is in database change page to home
frame.navigate("pages/home/home-page");
}
// navigates to home page without requiring login info (for testing)
frame.navigate("pages/home/home-page");
}
The post request doesn't work. I would like the console.logs in the server file to print the request. I think the problem is how I wrote the post request? Currently nothing happens.
Upvotes: 0
Views: 335
Reputation: 551
Fetch return a promise, you need to resolve it to actually make the POST
request. Try the following block of code.
fetch('http://localhost:3000/login', options)
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});
Upvotes: 1