im正在尝试从我的javascript应用程序连接到我的本地节点服务器路由(http://localhost:3000/user-ragnarok-controller/saveragnarokuser/),但没有收到任何响应。服务器正在接收请求并正在处理该请求,但是我无法在客户端得到响应。
我的JavaScript应用程序在localhost:80(Apache XAMPP)上运行,而我的节点服务器在localhost:3000上运行。
这是我的JavaScript代码,用于连接到节点服务器端点:
function handler() {
alert('handler');
if(invocation.readyState === XMLHttpRequest.DONE && invocation.status === 200) {
alert('entrei aqui');
console.log(invocation.responseText);
} else
alert('nao foi hj ' + invocation.status.toString());
}
function saveUser() {
alert('dourado ');
var eml = document.getElementById('emailInputRegister');
var user = document.getElementById('userInputText');
var sx = document.getElementById("sexInputSelected");
var selectedSex = sx.options[sx.selectedIndex].value;
var pwd = document.getElementById("passwordInputRegister");
var uri = 'http://localhost:3000/user-ragnarok-controller/saveragnarokuser/';
var body = {
'userid': user.value,
'userpass': pwd.value,
'email': eml.value,
'sex': selectedSex
};
invocation.open('POST', uri);
invocation.withCredentials = true;
invocation.setRequestHeader('Content-Type', 'application/json');
invocation.onreadystatechange = this.handler;
invocation.send(JSON.stringify(body));
}
这是我在Google Chrome控制台上的请求
现在让我们谈谈服务器端。在这里,我有一个用于CORS处理的中间件。
// Add headers
app.use(function (req, res, next) {
console.log('reqHeaders: ' + JSON.stringify(req.headers));
res.header('Access-Control-Allow-Origin', 'http://localhost');
res.header('Access-Control-Allow-Headers', 'content-type');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('Access-Control-Allow-Credentials', true);
if(req.method === 'OPTIONS')
return res.status(200).send({});
next();
});
CORS之后,服务器开始我的路线POST:
router.post('/saveragnarokuser',function(req,res,next){
console.log('######################### Iniciando saveragnarokuser.');
UserRagnarokController.addUser(req.body,function(err,count){
if(err){
console.log('entrei aqui error: ' + err);
res.json(err);
}
else{
console.log('entrei aqui ok');
var userObj = {
response: "OK"
};
res.status(200).json(userObj);
}
});
});
查看服务器日志,可以看到请求正在处理中,但是由于某种原因POST响应是-ms-。没有状态和执行时间。
reqHeaders: {"host":"localhost:3000","connection":"keep-alive","content-length":"88","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36","content-type":"application/json","accept":"*/*","origin":"http://localhost","sec-fetch-site":"same-site","sec-fetch-mode":"cors","sec-fetch-dest":"empty","referer":"http://localhost/co-cadastro/register.html?","accept-encoding":"gzip, deflate, br","accept-language":"pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7"}
######################### Iniciando saveragnarokuser.
myReqbody: {"userid":"fernandocabeca","userpass":"1234","email":"[email protected]","sex":"F"}
POST /user-ragnarok-controller/saveragnarokuser/ - - ms - -
entrei aqui ok
我的功能UserRagnarokController.addUser执行得很好,请购数据已成功填充到数据库中,我只需要在客户端(谷歌浏览器应用程序)获得此响应,我就没有错误也没有成功。