我正在尝试使用AJAX或req.body将一个变量添加到NODEJS



我想发送一个在客户端javascript中的变量/值。我这样做的原因是,当我尝试发送JSON时,我的req.body.domain返回时是未定义的,也是一样的,我尝试将其发送到nodejs路由。

客户端Ajax请求

function digIt() {
var xhr = new XMLHttpRequest();
const domain = document.getElementById("digTool").value;
const digToolInput = document.getElementById("digToolInput");
digToolInput.innerHTML = domain;
digToolInput.style.fontSize = "35px";
const usMap = document.getElementById("us-map");
usMap.classList.add("appear");
digToolInput.classList.add("moved");
console.log(domain);
myJSON = { "domain" : domain  };
console.log(JSON.stringify(myJSON));
xhr.open('POST', '/tools', true);
xhr.send(myJSON);
};

NodeJS接收AJAX请求的路由

router.post('/tools', (req, res, next) => {
console.log(req.body.myJSON);
mid.canYouDigIt(domain);
res.render('tools', {test: 'domain'});
next();
});

html/jade

doctype html
html(lang="en")
head
link(rel="stylesheet" type="text/css" href="./css/style.css")
link(rel="stylesheet" type="text/css" href="./css/animation.css")
link(href="https://fonts.googleapis.com/css?family=Cutive+Mono" rel="stylesheet")
link(href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Ubuntu" rel="stylesheet")

title Nymadic #{title}

body
section(id="container")
section(id="navWrapper")
img(id="logo" src="img/Nymadic_Logo_Edit_NEW.png" onclick="location='/'")
<!----- Navigation Menu ----->
div(id="navMenu")
ul
li(onclick="location='/'") Home
li(onclick="location='/about'") About
li(onclick="wikiOpen()") Wiki
li(onclick="toolsOpen()") Tools
if !currentUser
li(onclick="location='/login'") Login
else
li(onclick="location='/profile'") #[img( id="navProfileLogo" src="/img/if_ninja_479478.png")] Profile
li(id="navLogout" onclick="location='/logout'") Logout

<!----- Wiki Menu ----->
section(id="sideBar")
div
img(id="logoSideBar" src="img/Nymadic_Logo_Edit_NEW.png" onclick="location='/'")
form
input(id="searchBar" name="search" type="text" placeholder="Search for knowledge...")
ul
li( v-for="page in mediaList" v-bind:name="page.title" v-on:click="toggleDetails(page)") {{ page.title }}
div( id="descriptionWrapper" v-bind:class="{less: page.showDetail}" )
p( ) {{ page.description }}
p(v-if="page.author" size="8" ) Created By: {{ page.author }}
<!----- Tools Menu ----->
section(id="digToolWrapper")
form( id="digToolInput" )
ul
li #[input(id="digTool" name="domain" type="text" placeholder="Can you dig it?")]#[input(id="whois" value="whois" type="button" onclick="digIt()")] 

您已经打印了字符串化的JSON正文,但发送失败。在发送时也要执行同样的操作。

在发送JSON数据时,您应该使用JSON.stringify(data),因此在您的情况下,

xhr.send(JSON.stringify(myJSON));

如果可能的话,使用新的Web API,比如fetch((,而不是XHR。

获取API有更多的优点,如这里提到的

最新更新