Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
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 have been moved, edited, or deleted."

What can I do to fix this?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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'));
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

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))
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda