node.js - 如何在 Node.js 中发送 GET / POST 方法请求参数
问题描述
我无法在 nodejs 中获取服务器端的数据我是 node js 的新手!我正在使用快递!我在开发者控制台中看到的请求就像id=Bharadwaj&title=requestcheck
!
<!DOCTYPE html>
<html>
<head>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<meta charset="utf-8" />
<title>Bharadwaj</title>
</head>
<body>
<div id="contact">
<h1>Send an email</h1>
<div>
<input id="Bottle">
<button id="name_one">Click me</button>
</div>
</div>
</body>
<script>
$('#name_one').click(function() {
var json='{"id":"SomeId","title":"SomeTitle"}';
var obj=JSON.parse(json);
$.ajax({
url: "http://127.0.0.1:8080/putinto",
type: "POST",
dataType: "json",
data: obj,
contentType: "application/json",
cache: false,
timeout: 5000,
complete: function() {
//called when complete
console.log('process complete');
},
success: function(data) {
console.log(data);
console.log('process sucess');
},
error: function() {
console.log('process error');
},
});
})
</script>
</html>
这是我的服务器代码。
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/',(req,res)=>{
res.send("hello express");
});
app.post('/putinto', function(req, res) {
//I want to get req.id, req.title
res.send("Hello World");
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
请帮我 。如何在服务器端获取 id 和 title 并将其作为响应发送!
在职的 :
$('#name_one').click(function() {
var json='{"id":"SomeId","title":"SomeTitle"}';
var obj=JSON.parse(json);
$.ajax({
url: "http://localhost:8080/putinto",
method: "POST",
data: obj,
cache: false,
timeout: 5000,
complete: function() {
//called when complete
console.log('process complete');
},
success: function(data) {
console.log(data);
console.log('process sucess');
},
error: function() {
console.log('process error');
},
});
})
这对我来说很好用!
解决方案
在客户端: 您在客户端的代码应该是:
$.post('http://127.0.0.1:8080/putinto', { id: "54147512865132", title: "hello"},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
在服务器:
您在req.body
. 标题在req.headers
app.post('/putinto', function(req, res) {
//I want to get req.id, req.title
console.log("Headersdata:", req.headers) // Here you will get JSON.
console.log("params data:", req.params) // Here you will get JSON.
console.log("JSON data:", req.body) // Here you will get JSON.
res.send("Hello World");
});
检查JSON object
您从客户端发送的终端。
推荐阅读
- css - CSS 清单 2 个单独的列表,每行有 2 个元素,依此类推
- objective-c - 有没有办法在条形图上方和下方添加两个文本值?在 ios danielgindi 图表中
- python-3.x - 带有要作为数据框打开的列表列表的文本文件
- date - 查找今天日期的前一天和今天日期之后的日期
- javascript - 从模板字符串的末尾删除“,”逗号
- vuejs2 - 在 vue-cli 中将分钟转换为小时的全局函数
- javascript - Cytoscape.js - 查找所有公共节点并保留它们
- reactjs - 当某些为空时,React/Spring-boot 无法显示 @ManyToOne 关系
- boolean - 逻辑门求解与模拟
- javascript - 我无法在我的搜索字段中书写,但建议功能有效。我该如何解决?