简体   繁体   中英

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. I tried doing this using fetch but I get this error:

Fetch API cannot load file:///C:/api/register. URL scheme "file" is not supported.

This is the code:

index.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. 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. Either serve the file from your server, or fetch 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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