简体   繁体   English

为什么我不能向我的 Node.js Express 服务器发出 POST 请求

[英]Why can't I make a POST request to my Node.js Express server

I am trying to create a basic user registration system.我正在尝试创建一个基本的用户注册系统。 All I just want right now is that once I register with the html form, I should be able to console.log it in the server.我现在只想在使用 html 表单注册后,我应该能够在服务器中进行控制台登录。 I tried doing this using fetch but I get this error:我尝试使用 fetch 执行此操作,但出现此错误:

Fetch API cannot load file:///C:/api/register.获取 API 无法加载 file:///C:/api/register。 URL scheme "file" is not supported.不支持 URL 方案“文件”。

This is the code:这是代码:

index.html:索引.html:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <title>Register</title>
    </head>
    <body>
        <h1>Registration</h1>
        <form id="reg-form">
            <input type="text" placeholder="Username" id="username" autocomplete="off"/>
            <input type="password" placeholder="Password" id="password"/>
            <input type="submit" value="Submit Form"/>
        </form>
    </body>
    <script>
        const form = document.getElementById('reg-form')
        
        form.addEventListener('submit', registerUser)
        
        async function registerUser(event) {
            event.preventDefault()
            
            const username = document.getElementById('username').value
            const password = document.getElementById('password').value
            
            const result = fetch('/api/register', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({username, password})
            }).then(res => res.json())
            
            console.log(result)
        }
    </script>
</html>

Express Server:快递服务器:

const express = require('express')
const path = require('path')
const bodyParser = require('body-parser')
const app = express()

app.use(bodyParser.json())

app.post('/api/register', async (req, res) => {
    console.log(req.body)
    res.json({status: 'ok'})
})

app.listen(4000, () => console.log('Server up at 4000'))

I also tried doing the POST request directly from the HTML form element by setting the method attribute to POST and the action attribute pointing to the post route in my express server.我还尝试直接从 HTML 表单元素发出 POST 请求,方法是将方法属性设置为 POST,并将操作属性设置为我的 express 服务器中的 post 路由。 When I try to submit the form, it redirects me to an empty page that says "Your file couldn't be accessed. It may has been moved, edited or deleted."当我尝试提交表单时,它会将我重定向到一个空白页面,上面写着“您的文件无法访问。它可能已被移动、编辑或删除。”

What can I do to fix this?我能做些什么来解决这个问题?

You're opening the html file manually, not serving it from the server, so /api/register isn't going to your backend.您正在手动打开 html 文件,而不是从服务器提供它,因此/api/register不会进入您的后端。 Either serve the file from your server, or fetch localhost:4000/api/register从您的服务器提供文件,或获取localhost:4000/api/register

To serve your file from the server, you can do this:要从服务器提供文件,您可以执行以下操作:

const path = require('path');

...

app.get('/', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../relative/path/to/index.html'));
});

Instead of fetching /api/register try http://localhost:4000/api/register而不是获取/api/register尝试http://localhost:4000/api/register

also to print the result try this:也打印结果试试这个:

fetch('http://localhost:4000/api/register', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({username, password})
            })
            .then(res => res.json())
            .then(data => console.log(data))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM