邮差POST请求的作品,但阿贾克斯后没有。一遍遍检查客户端的js
曾经在计算器和男孩的第一个问题,我需要一个答案。我的问题是,我有一个端点创建一个项目,它的工作原理,当我送与邮差POST请求。我使用节点,并明确:
router.post("/", jwtAuth, (req, res) => {
console.log(req.body);
const requiredFields = ["date", "time", "task", "notes"];
requiredFields.forEach(field => {
if (!(field in req.body)) {
const message = `Missing \`${field}\` in request body`;
console.error(message);
return res.status(400).send(message);
}
});
Task.create({
userId: req.user.id,
date: req.body.date,
time: req.body.time,
task: req.body.task,
notes: req.body.notes
})
.then(task => res.status(201).json(task.serialize()))
.catch(err => {
console.error(err);
res.status(500).json({ message: "Internal server error" });
});
});
当我与邮差和记录了正确的价值观的REQ体发送端点的工作。
但是,当我把我的Ajax请求,我的服务器代码的记录作为req.body一个空对象(“{}”)。因为邮差的工作,我相信这个问题是我的客户端JavaScript,但我不能发现问题。我和其他人看着它一百万次,但就是无法找到问题。这里是我的客户端的JavaScript:
//User submits a new task after timer has run
function handleTaskSubmit() {
$(".submit-task").click(event => {
console.log("test");
const date = $(".new-task-date").text();
const taskTime = $(".new-task-time").text();
const task = $(".popup-title").text();
const notes = $("#task-notes").val();
$(".task-notes-form").submit(event => {
event.preventDefault();
postNewTask(date, taskTime, task, notes);
});
});
}
function postNewTask(date, taskTime, task, notes) {
const data = JSON.stringify({
date: date,
time: taskTime,
task: task,
notes: notes
});
//Here I log all the data. The data object and all its key are defined
console.log(data);
console.log(date);
console.log(taskTime);
console.log(task);
console.log(notes);
const token = localStorage.getItem("token");
const settings = {
url: "http://localhost:8080/tasks",
type: "POST",
dataType: "json",
data: data,
contentType: "application/json, charset=utf-8",
headers: {
Authorization: `Bearer ${token}`
},
success: function() {
console.log("Now we are cooking with gas");
},
error: function(err) {
console.log(err);
}
};
$.ajax(settings);
}
handleTaskSubmit();
回答如下:
我会怎么做:
- 更改头“应用/ JSON的”到“应用程序/ x-WWW的形式了urlencoded”,因为official docs对前者没有资料。
- 停止使用$阿贾克斯和获得舒适与XHR请求,因为从CDN jQuery是有时一个烂摊子时,CDN获取的laggy和XHR是土生土长的立即执行和使用。是的,它是一个代码一塌糊涂,但你总是知道它是不是内库逻辑的事情,但是你自己的问题。你盲目使用库,这里面隐藏XHR,你不知道如何提出正确的问题“XHR POST方法的文档”,因为你还不熟悉下面的基本技术。
保存此并导入变量
var httpClient = {
get: function( url, data, callback ) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
var readyState = xhr.readyState;
if (readyState == 4) {
callback(xhr);
}
};
var queryString = '';
if (typeof data === 'object') {
for (var propertyName in data) {
queryString += (queryString.length === 0 ? '' : '&') + propertyName + '=' + encodeURIComponent(data[propertyName]);
}
}
if (queryString.length !== 0) {
url += (url.indexOf('?') === -1 ? '?' : '&') + queryString;
}
xhr.open('GET', url, true);
xhr.withCredentials = true;
xhr.send(null);
},
post: function(url, data, callback ) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
var readyState = xhr.readyState;
if (readyState == 4) {
callback(xhr);
}
};
var queryString='';
if (typeof data === 'object') {
for (var propertyName in data) {
queryString += (queryString.length === 0 ? '' : '&') + propertyName + '=' + encodeURIComponent(data[propertyName]);
}
} else {
queryString=data
}
xhr.open('POST', url, true);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(queryString);
}
};
用法是在jQuery简单:httpClient.post(URL,数据,(XHR)=> {})
- 检查您是否有在app.js身体解析器建立
var bodyParser = require('body-parser'); app.use(bodyParser.json()); // get information from html forms app.use(bodyParser.urlencoded({ extended: true })); // get information from html forms
- 如果体解析器被建立尝试改变头为“的multipart / form-data的”或“文本/纯”。
- 对于刚刚起见检查req.query
干杯! :)