因此,我正在构建一个配方搜索引擎,我想将用户对类别的选择转移到服务器,以便在API调用中使用它。以下是一些代码:
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);
}
服务器端
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和数据变量肯定得到了它应该得到的,我已经登录了,它运行得很好。那么,无论我在客户端记录承诺还是在服务器端记录数据,我都只得到{}
,有什么想法吗?
使用JSON内容类型。后端应该返回数据:
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);
});
和客户端:
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);
});
-
您的后端部分应该返回一个响应,以便按您期望的方式工作。
-
您只处理POST请求,但还需要一个get请求。
app.get('/data', (request,response) => {
return response.json({
// JSON data here
})
})