我正在使用sails.js v0.11.1。 在我的routes.js文件中,我写了这条路线:
'POST /user' : {
model: 'user',
blueprint: 'create'
},
我正在向/user
发送一个POST请求(通过postman),并将其发送到正文中:
{
userName : "firstUser",
password : "secretPwd5779",
firstName : "William",
lastName : "Askey"
}
但是我收到了这个回复:
{
"error": "E_VALIDATION",
"status": 400,
"summary": "4 attributes are invalid",
"model": "User",
"invalidAttributes": {
"userName": [
{
"rule": "string",
"message": "`undefined` should be a string (instead of \"null\", which is a object)"
},
{
"rule": "required",
"message": "\"required\" validation rule failed for input: null"
}
],
"password": [
{
"rule": "string",
"message": "`undefined` should be a string (instead of \"null\", which is a object)"
},
{
"rule": "required",
"message": "\"required\" validation rule failed for input: null"
}
],
"firstName": [
{
"rule": "string",
"message": "`undefined` should be a string (instead of \"null\", which is a object)"
},
{
"rule": "required",
"message": "\"required\" validation rule failed for input: null"
}
],
"lastName": [
{
"rule": "string",
"message": "`undefined` should be a string (instead of \"null\", which is a object)"
},
{
"rule": "required",
"message": "\"required\" validation rule failed for input: null"
}
]
}
}
根据Sails.js documentation我正确地写了路线。
通过网址参数发出此请求(即向/user?userName=firstUser&password=secretPwd5779&firstName=William&lastName=Askey
发送请求的工作正常。如何在不通过网址参数发送数据的情况下使其生效?
答案 0 :(得分:2)
标准方式:
这是你的表格:
<form class="ajax" method="post" action="/user">
<input name="userName">
<input name="password">
<input name="firstName">
<input name="lastName">
<button type="submit">CREATE</button>
</form>
<div id="result"></div>
这是frontend js part(jquery是必需的):
$(function(){
$('form.ajax').on('submit', function(e){
e.preventDefault();
var method = $(this).attr('method');
var url = $(this).attr('action');
var data = $(this).serializeArray();
$.ajax({
url: url,
method: method,
data: data,
success: function(response) {
$('#result').html(JSON.stringify(response));
},
error: function() {
alert('Error! Try again later.');
}
});
});
});
但是你要发送json正文,所以必须启用将json正文转换为request.body的中间件。
它被称为身体解析器。见截图:http://joxi.ru/752aJJbhj45DA0
答案 1 :(得分:2)
@ num8er的答案对我来说很有洞察力(作为新手sailsjs / node程序员),但我的问题实际上是由流氓pm2实例引起的。
我正在发出的请求被发送到一个流氓实例,其中我写的路由/更改没有反映在代码中。希望这可以帮助那些人。