![](/img/trans.png)
[英]I get error when sending data using express from node server to client side JavaScript
[英]sending the value from javascript(client side) to express (server side)
我在javascript中创建HTML DOM,您将看到以下代码。 现在,我想将在javascript中创建的输入值发送到服务器端。 我的服务器是使用node.js和express框架创建的。 将值发送到服务器端后,我想将此值保存在json文件中。 我知道如何读写json文件,但是我的问题是发送此值。 这是我的JavaScript代码和表达代码。 在javascript代码中,我要发送inTask变量,在服务器代码中,我要在app.post
接收此值。
1.javascript代码
let newTask = [];
function addInput() {
document.getElementById("link").style.display = "none";
var input = document.createElement("input");
input.type = "text";
input.setAttribute("id", "inValue");
document.getElementById("input").appendChild(input);
var addBtn = document.createElement("button");
var text = document.createTextNode("Add Task");
addBtn.appendChild(text);
addBtn.addEventListener("click", addTask);
document.getElementById("input").appendChild(addBtn);
}
function addTask() {
var inTask = document.getElementById("inValue").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xhttp.send(document.getElementById("inValue").value);
}
var express = require("express"); var bodyParser = require("body-parser"); var app = express(); var fs = require('fs'); app.use(express.static(__dirname + "/static")); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended:true })); app.get("/" , function (req, resp, next) { resp.sendFile(__dirname + "/static/index.html"); }) ; app.post("/login" , function (req, resp, next) { var jsonData = req.body.inValue; fs.writeFile("data.json", jsonData, function(err) { if(err) { return console.log(err); } }); res.json(jsonData); }); app.listen(3000); console.log("app running on port 3000");
您希望服务器文件中有一个json-Data,但不发送json-Object。 交换xhttp.send(document.getElementById("inValue").value);
同
xhttp.send(JSON.stringify( { inValue: document.getElementById("inValue").value });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.