[Fixed] HTTP empty string

Issue

I am writing a simple script to send a url to an express server. When I want to console.log the req.body I get an empty string, even though I use a parser. Can you help me, getting this to work?

Client

document.addEventListener('keypress', logKey);

const API_URL = 'http://localhost:8000/bilder';

var image = document.getElementsByTagName('img')[0].src;

function logKey(e) {
const Http = new XMLHttpRequest();

Http.open("POST", API_URL);
Http.setRequestHeader('Content-Type', 'application/json');
Http.send(JSON.stringify(image));

Http.onreadystatechange = (e) => {
console.log(Http.responseText)
}
}

Server

const express = require('express')
const app = express();
var cors = require('cors')
const port = 8000;


app.use(cors());

app.use(express.json());


app.post('/bilder', (req, res) => {
    console.log(req.body)
    res.send("hello world")
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}!`)
});

Solution

I got it. The problem was in the header of the post and in the parser on the server. i had to add xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); to the post on the client and on the backend i had to use app.use(express.urlencoded()); as a parser. Using simply express was not efficent. So I learned, that the header needs the same content-type as the parser in the backend.

Thanks alot everyone and best regards

Leave a Reply

(*) Required, Your email will not be published