I create the HTML DOM in javascript that you see the below code. Now, I want send the value of input that I created in javascript to server side. My server that created with node.js and express framework. After sending the value to server side, I want to save this value in my json file. I know how to read and write json file, but my problem is sending this value. Here is my javascript code and express code. In javascript code I want send the inTask variable and in the server code I want to receive this value in app.post
.
1.javascript code
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");
You expect a json-Data in your server file, but you don't send a json-Object. Exchange xhttp.send(document.getElementById("inValue").value);
with
xhttp.send(JSON.stringify( { inValue: document.getElementById("inValue").value });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.