[英]How to include a User ID object in an Ajax call
我开始学习 web 开发,我有一个客户端服务器项目,用户可以在其中进行身份验证,然后存储他们的血压读数。 我的身份验证部分正在工作,但在存储血压读数方面遇到了困难。 我已经使用 curl 验证了所有功能都可以工作,但是当我尝试创建血压读数时,我从服务器收到错误。 我认为我的问题是我不知道如何在 Ajax 调用中将用户 ID 作为 object 包含在内。 非常感激任何的帮助。
这是有效的 curl 脚本:
API="http://localhost:4741"
URL_PATH="/readings"
curl "${API}${URL_PATH}" \
--include \
--request POST \
--header "Content-Type: application/json" \
--header "Authorization: Bearer ${TOKEN}" \
--data '{
"reading": {
"systolic": "'"${S}"'",
"diastolic": "'"${D}"'",
"pulse": "'"${P}"'"
}
}'
echo
以下是血压读数的示意图:
const mongoose = require('mongoose')
const readingSchema = new mongoose.Schema({
systolic: {
type: Number,
required: true
},
diastolic: {
type: Number,
required: true
},
pulse: {
type: Number,
required: true
},
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
}
}, {
timestamps: true
})
module.exports = mongoose.model('Reading', readingSchema)
以下是在服务器应用程序上创建的血压读数路线:
// CREATE
// POST /readings
router.post('/readings', requireToken, (req, res, next) => {
// set owner of new reading to be current user
req.body.reading.owner = req.user.id
Reading.create(req.body.reading)
// respond to succesful `create` with status 201 and JSON of new "reading"
.then(reading => {
res.status(201).json({ reading: reading.toObject() })
})
// if an error occurs, pass it off to our error handler
// the error handler needs the error message and the `res` object so that it
// can send an error message back to the client
.catch(next)
})
这是对 API 的 Ajax 调用。
// Create a reading
const readingCreate = function (data) {
let dataToSend = [{ user: store.user._id }, { data }]
dataToSend = JSON.stringify({ dataToSend })
return $.ajax({
method: 'POST',
url: config.apiUrl + '/readings',
data: dataToSend,
headers: {
ContentType: 'application/json',
Authorization: 'Bearer ' + store.user.token
}
})
}
这是我从 Chrome 开发工具中看到的:
来自 Chrome 网络标头:
请求 URL: http://localhost:4741/readings 请求方法: POST 状态码: 500 内部服务器错误远程地址: [::1]:4741 推荐人策略: strict-origin-when-cross-origin
请求标头:
Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Authorization: Bearer 62613675961deb85f4f11ecfca5239ac Connection: keep-alive Content-Length: 30 Content-Type: application/x-www-form -urlencoded; charset=UTF-8 ContentType: application/json Host: localhost:4741 Origin: http://localhost:7165 Referer: http://localhost:7165/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-获取站点:同站点用户代理:Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.192 Safari/537.36
这是服务器控制台所说的:
20:47:52 GMT-0600(中部标准时间):类型错误:无法在 router.post (/Users/Ken/sei/projects/project2/bp_tracker/app/routes/reading_routes.js: 62:26)
您正在发送一个带有用户 ID 的数组,但出于某种原因将req.user.id
而不是req.body.user
的值分配给了reading.owner
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.