json 【Node.js,Express】POST受信サンプル
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了json 【Node.js,Express】POST受信サンプル相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>POST送信テスト</title>
<script>
function getData() {
$.ajax({
url: 'http://localhost:8080/req-post',
type: 'POST',
data: {
'id': 'name'
},
dataType: 'text'
}).done(function( data, textStatus, jqXHR ) {
//成功
console.log("成功")
}).fail(function( jqXHR, textStatus, errorThrown) {
//失敗
console.log("失敗")
}).always(function( jqXHR, textStatus) {
//通信完了
console.log("通信完了")
});
}
</script>
</head>
<body>
<button onclick="getData()">POST送信</button>
<!-- jQuery -->
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
</body>
</html>
var bodyParser = require('body-parser') //JSON受け取り用にbody-parserモジュール呼び出し
var express = require('express')
var app = express()
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.post('/req-post', function (req, res) {
// リクエストボディを出力
console.log(req.body)
// クロスオリジンを許可するなら以下の2行を利用
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
res.end()
})
app.listen(process.env.PORT || 8080)
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "main.js",
"dependencies": {
"body-parser": "^1.16.0",
"express": "^4.14.1"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
以上是关于json 【Node.js,Express】POST受信サンプル的主要内容,如果未能解决你的问题,请参考以下文章
Node.js、Express、jQuery.param() - 从 JSON 中删除引号
如何在 node.js + Express 中同时支持 json 和 jsonp 响应?
在单个 Node.js + Express 响应中发送图像和 JSON 数据
使用 Express 4 在 Node.js 中解析 JSON 发布请求
如何在 express node.js POST 请求中接收 JSON?
使用 Node.js 和 Express 将 JSON 数据集显示为表格