如何在 Nativescript 中通过 Fetch 发出 post 请求?

How do you make a post request via Fetch in Nativescript?

我有一个 server.js 文件。使用 post 请求 (/login)。它看起来像这样:

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);
})

我在 NativeScript 中也有一个函数,它应该在按下按钮时发出 post 请求(提取所在的位置)。它看起来像这样:

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");
}

post 请求无效。我希望服务器文件中的 console.logs 打印请求。我认为问题是我如何编写 post 请求?目前没有任何反应。

获取 return 承诺,您需要解决它才能实际发出 POST 请求。试试下面的代码块。

fetch('http://localhost:3000/login', options)
          .then((response) => response.json())
          .then((result) => {
            console.log('Success:', result);
          })
          .catch((error) => {
            console.error('Error:', error);
          });