[英]POST http://localhost:3000/data 400 (Bad Request) when trying to send data from client to server
Hey guys so i've got some problem with sending data from client-side to server-side.嘿伙计们,所以我在将数据从客户端发送到服务器端时遇到了一些问题。 Basically i have a function that on click is setting variable called categorySearch to a string eg categorySearch = "pork" and send it to server;
基本上我有一个 function 在点击时将名为 categorySearch 的变量设置为字符串,例如 categorySearch = "pork" 并将其发送到服务器; But for some reason i keep getting error mentioned in the title.
但由于某种原因,我不断收到标题中提到的错误。 Here's some code: Client Side
这是一些代码:客户端
function getRecipes(category){
const categorySearch = category.alt;
const options = {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: categorySearch
}
const response = fetch('/data', options);
console.log(response);
}
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, repsonse) => {
console.log(request.body);
})
Not sure what i did wrong, i haven't worked much with backend so don't have much knowledge either, any help very appreciated:)不知道我做错了什么,我在后端工作不多,所以也没有太多知识,非常感谢任何帮助:)
My end-goal for that is to be able to send the data that users enters or in this case clicks on to the server, then in the server-side make an api call to the search engine, take the data i need, send it back to client-server and display it on the page.我的最终目标是能够将用户输入或在这种情况下点击的数据发送到服务器,然后在服务器端对搜索引擎进行 api 调用,获取我需要的数据,发送它返回客户端-服务器并将其显示在页面上。
Reason :-原因:-
The 400 Bad Request Error is an HTTP response status code that indicates that the server was unable to process the request sent by the client due to invalid syntax 400 Bad Request Error 是一个 HTTP 响应状态码,表示由于语法无效,服务器无法处理客户端发送的请求
as per your code your sending data from client as json and retrieving that in your server as plain text, so instead of sending it as application/json
use text/plain
or remove that header part so it will work fine, check out the below-attached code.根据您的代码,您从客户端发送数据为 json 并在服务器中以纯文本形式检索该数据,因此不要将其作为
application/json
发送,而是使用text/plain
或删除 header 部分,以便它可以正常工作,请查看以下内容 -附代码。
Client-side:-客户端:-
function getRecipes(category){
const categorySearch = category.alt;
const options = {
method: 'POST',
headers: {
'Content-type': 'text/plain', // or remove this headers section
},
bodydata: categorySearch
}
const response = fetch('/data', options);
console.log(response);
}
Server side:服务器端:
app.post('/data', (request, repsonse) => {
console.log(request.body.bodydata);
})
hope this will give you some idea about the error.希望这会让您对错误有所了解。 read here more about 400 error
在此处阅读有关400 错误的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.