【发布时间】:2018-09-24 14:05:08
【问题描述】:
在过去的 6 个小时里,我一直在试图弄清楚,但我没有想法..
我想要完成的事情:
我想显示一个像这样的 JSON 数据
movie {title: " xxxxx", seed: "number", url: "zzzzzzzzz"}
我想将它显示在我的节点服务器上(通过玉),但我现在完成的是使用以下代码通过 POST 请求将它从网站发送到我的节点服务器:
我的 JS 脚本
var http = new XMLHttpRequest();
var url = "http://localhost:8080/";
var params = arr; <------ My JSON data
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(params);
在我的网站上的谷歌浏览器开发者工具中使用上述代码后,我实际上有该数据,我在我的节点中收到 JSON 数组,这是我的节点代码:
我的 app.js 节点服务器
const http = require("http");
const express = require('express');
const app = express();
const myParser = require('body-parser');
app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.static(__dirname + '/public'))
app.use(myParser.urlencoded({ extended: false }));
app.use(myParser.json())
var allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
app.use(allowCrossDomain);
app.get('/', function (req, res, next) {
res.render('index');
})
app.get('/tl', function (req, res, next) {
res.render('tl');
})
app.post("/", function (req, res) {
response = {
first_name: req.body
};
console.log('SHOW ME BODY')
console.log(req.body);
res.send('You sent: this to Express');
});
app.listen(8080);
这就是我在节点命令提示符中收到的内容:
{ '[{"title":" SOME-MOVE-TITLE","seed":"NUMBER","url":"https://SOMEURLS.COM', etc. etc. etc.
最后是我的 layout.jade 文件
doctype
html
head
title Bolo Node Server
link(rel="stylesheet", type="text/css", href="stylesheet/style.css")
body
header
h1 My Site
block content
footer
p Running on node with Express, Jade and Stylus
还有 index.jade
extend layout
block content
p= 'Block content works'
script.
if req.body != undefined
div(id='data')= req.body
关于如何显示收到的 json 数组,我真的没有办法了……请帮帮我
更新
我的 index.jade
扩展布局
block content
p= 'Block content works'
div(id='data')
pre
test= jsonString
我的 app.js 现在看起来像这样:
app.get('/', function (req, res, next) {
res.render('index');
})
app.post("/", function (req, res) {
// Get string representation
var jsonString = JSON.stringify(req.body || {}); // use JSON.stringify(req.body || {}, null, 2) for formatted JSON
console.log(jsonString);
res.render('index', {test: jsonString});
//res.send('You sent: this to Express');
});
我在节点命令提示符中看到数据,但在我的本地网站http://localhost:8080/ 上看不到它,div(id='data') 显示为空.. 什么都没有,我如何在那里获取 jsonString? ?我想让它显示我本地网站上的数据..
**
更新
**
我最终只是将数据放入 sqlite3 数据库,然后通过 GET 请求检索数据,最后将其放入我的玉模板。我以为我可以绕过而不使用 sqlite3,但我不知道怎么做。
【问题讨论】:
标签: javascript json node.js post request