I have component for SQL queries and when I want to send any query to API-server backend crash down because MySQL see empty string like a my request. My backend is working good because when I test it from postman.exe everything is fine.
My component with submit is on localhost:3000 and api on localhost:5000.
Here is my sending method:
submitData= () =>{
const { queryFromEditor } = this.props;
let queryFromEditorString = queryFromEditor.join(' ');
console.log(queryFromEditorString);
let xhr = new XMLHttpRequest();
xhr.open("POST", 'http://localhost:5000/api/query', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
"value": queryFromEditorString,
}));
}
Here is my post method
app.post('/api/query', (req, res) => {
console.log(`\n Query input : ${JSON.stringify(req.body)}`);
let queryInput = JSON.stringify(Object.values(req.body));
queryInput = queryInput.slice(1,-1);// Opravit, aby to nevypadalo tak blbě
queryInput = queryInput.slice(1,-1);
let queryOutput;
db.query(queryInput, (err, result) =>{
if(err) throw err+' : '+queryInput;
queryOutput = result;
console.log("\nQuery output "+ JSON.stringify(queryOutput));
res.json(queryOutput);
});
});
Problem was on server.
Easy fix: add "app.use(express.json());"