Home > Software design >  Sending data formData througt Javascript to Express API
Sending data formData througt Javascript to Express API

Time:10-01

So, when i handle a post request througt javascript, i send the data to the api, and i don't know how to log the data in the API.

What i tried

app.post("/register", (req,res) => {
    res.render("register/register", {});
    -> i tried to log it as req.query, req.params or req.body console.log(req.query)
})

JS code:

document.querySelector("#regForm").addEventListener('submit', e => {
    e.preventDefault();
    let username = document.querySelector("#username").value;

    let formData = new FormData(document.querySelector("#regForm"));
    
    console.log([...formData]);

    let data = JSON.stringify([...formData]);
    console.log(data)
        
        const request = new XMLHttpRequest();
        request.open("POST", '/register');
        request.send(data);
    })

Edit: The full API code:

const express = require("express");
const path = require("path");
var bodyParser = require('body-parser')

const app = express();
const port = process.env.POST || "8080";

var jsonParser = bodyParser.json()
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.listen(port, () => {
    console.log(`Running on port ${port}`);
})
// middleware & static files
app.use(express.static('public'));
app.use(express.json());

app.set("view engine", "ejs");

app.use(express.static(__dirname   '/src'));
app.get("/profile/:name", (req,res) => {
    res.render("profile", {username:req.params.name});
})

app.get("/register", (req,res) => {
    res.render("register/register", {});
})

app.post("/register", jsonParser, (req,res) => {
    res.render("register/register", {});
    console.log(req.body)
})

Answer to LakiMancic - The error: error

And nothing works. Can you help me? Thanks!

CodePudding user response:

Try to specify Content-Type of your XMLHttpRequest with

request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

After request.open(...); and before request.send(...);

Update ( Full Code that worked for me ):

const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());
app.use(express.urlencoded({
  extended: true
}));

app.get('/', (req, res) => {
    res.sendFile(__dirname   '/main.html');
});

app.post("/register", (req,res) => { 
    console.log(req.body)
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});
document.querySelector("#regForm").addEventListener('submit', e => {
            e.preventDefault();
            let username = document.querySelector("#username").value;

            let formData = new FormData(document.querySelector("#regForm"));
            
            console.log([...formData]);

            let data = JSON.stringify([...formData]);
            console.log(data)
            
            const request = new XMLHttpRequest();
            request.open("POST", '/register');
            request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            request.send(data);
        })
  • Related