我正在尝试对我创建的 RESTful API 进行简单的 POST 调用。我使用 Angular 作为客户端,nodejs 作为服务器,mongodb+express+ multer作为数据库。
当使用POSTman测试后端时,对象被正确创建,从 req.body 获取数据。在我的 Angular 控制器的 createProject 方法中,我在发布到 API 之前打印出我的 formData。表单数据看起来正确。当正确的表单数据被发布到工作服务器时,req.body 显示为空。
这是我的相关服务器代码:
app.use(express.static(__dirname + '/public'));
app.use(multer({ dest: 'public/uploads/'}));
router.route('/projects') // accessed at //localhost:8080/api/projects
.post(function(req, res) {
console.log(req.body); // returns empty set
var project = new Project();
project.name = req.body.name;
project.description = req.body.description;
project.newComments = 0;
project.newPosts = 0;
//project.imageURL = req.body.imageURL;
project.save(function(err) {
if (err)
res.send(err);
Project.find(function(err, projects) {
if (err) res.send(err);
res.json(projects);
});
});
})
app.use('/api', router); …Run Code Online (Sandbox Code Playgroud) 考虑以下方法:
public async Task<string> GetNameOrDefaultAsync(string name)
{
if (name.IsNullOrDefault())
{
return await GetDefaultAsync();
}
return name;
}
Run Code Online (Sandbox Code Playgroud)
当name被提供,不等待将发生在方法执行的,但这种方法会正确编译。
但是,此方法将产生如下所示的构建警告:
public async Task<string> GetDefaultAsync()
{
return "foobar";
}
Run Code Online (Sandbox Code Playgroud)
[CS1998] This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
为什么它GetNameOrDefaultAsync可以在不等待的情况下返回,并且不会导致编译器警告,但GetDefaultAsync必须等待才能编译?
执行以下操作会有所改进吗?:
public async Task<string> GetNameOrDefaultAsync(string name)
{
if (name.IsNullOrDefault())
{
return await GetDefaultAsync();
} …Run Code Online (Sandbox Code Playgroud) angularjs ×1
async-await ×1
asynchronous ×1
c# ×1
express ×1
forms ×1
node.js ×1
post ×1
task ×1