Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda