So I am building a recipe search engine and I want to transfer the user's choice of the category to the server so I can use it in API call. Here's some code :
CLIENT-SIDE
function getRecipes(category){
const categorySearch = category.alt;
let data = {
categoryChoice: categorySearch
}
console.log(data);
let options = {
method: 'POST',
headers: {
'Content-type': 'text/plain'
},
body: JSON.stringify(data)
}
const promise = fetch('/data', options);
console.log(promise);
}
SERVER-SIDE
const express = require('express');
const app = express();
const fetch = require('node-fetch');
require('dotenv').config();
const API_KEY = process.env.API_KEY;
const port = process.env.PORT || 3000;
app.listen(port, () => console.log('listening at 3000'));
app.use(express.static('public'));
app.use(express.json({ limit: "1mb"}));
app.post('/data', (request, response) => {
let data = request.body;
console.log(data);
response = "Got data";
console.log(response);
})
categorySearch and data variables definitely get what it should, I have logged in and it's working fine. Then whether I log promise in client-side or data in server-side I only get {}
, any ideas?
Working with JSON content type. Backend-Side should be returning data:
app.post('/data', (request, response) => {
let data = request.body;
let gotData;
if(data.categoryChoice == "option1")
gotData = {id:1, label:"val 1", q:data.categoryChoice};
else
gotData = {id:2, label:"val 123", q:data.categoryChoice};
response.json(gotData);
});
And the Client-Side:
let data = { categoryChoice: "option1" };
let options = {
method: 'POST',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(data)
}
const promise = fetch('/data', options);
promise.then(response => {
if (!response.ok) {
console.error(response);
} else {
return response.json();
}
}).then(result => {
console.log(result);
});