简体   繁体   中英

POST method returns empty object in both client and server

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);
});
  1. Your backend part should be returning a response for it to work the way you expect it.

  2. You are only handling a POST request but you also need a get request.

app.get('/data', (request,response) => {
    return response.json({
    // JSON data here
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM