[英]Is there a way to send a variable from a client.js file to your node.js file?
I am trying to pass in a product number from my client to my server so I can save it to a database. 我正在尝试将产品编号从我的客户端传递到我的服务器,以便将其保存到数据库中。 I've tried almost 100 different ways to print out the "prod" variable but nothing is working.
我已经尝试了近100种不同的方法来打印出“prod”变量,但没有任何工作。
I already have body-parser and other things included in my code. 我已经在我的代码中包含了body-parser和其他东西。 Is there some small thing I'm doing wrong?
有什么小事我做错了吗? if so how should I edit my client file or server file to be able to pass in "prod" from the client to server.
如果是这样,我应该如何编辑我的客户端文件或服务器文件,以便能够将“prod”从客户端传递到服务器。
As of right now if just says undefined
截至目前,如果只是说
undefined
Client.js: Client.js:
function addToCart(prod1) {
fetch( '/addToCart' , { method: ' POST ', body: ' prod= ' + prod1 });
}
server.js: server.js:
app.post("/addToCart", (req, res) => {
console.log(req.body.prod);
});
I expect whatever "prod" is, to be visible in my server file file when I console.log it out to the screen 我希望无论什么“prod”都可以在我的服务器文件文件中看到我在console.log它出现在屏幕上
Add application/json
as header's content type and use JSON.stringify({yourKey:yourData})
as the body. 将
application/json
添加为标头的内容类型,并使用JSON.stringify({yourKey:yourData})
作为正文。
Client: 客户:
function addToCart(prod1) {
fetch( '/addToCart' , {
headers: { "Content-Type": "application/json" },
method: ' POST ',
body: JSON.stringify({prod : prod1 })
});
}
Server: 服务器:
app.post("/addToCart", (req, res) => {
console.log(req.body.prod);
});
Why you don't try to send a json object instead a string? 为什么不尝试发送json对象而不是字符串?
data = {
prod: prod1
}
function addToCart(data) {
fetch( '/addToCart' , { method: ' POST ', body: JSON.stringify(data) });
}
The first problem I see here is that you donpt shot the content-type of your client request. 我在这里看到的第一个问题是你拍摄了客户请求的内容类型。 If you use for example
如果您使用例如
headers: { 'Content-Type': 'application/json' }
than the correct way to pass POST data is: 比传递POST数据的正确方法是:
body: JSON.stringify({prod: prod1})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.