小编Ben*_*eds的帖子

在 Angular 中发布时表单数据是正确的,但节点中的 req.body 为空?

我正在尝试对我创建的 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)

forms post node.js express angularjs

5
推荐指数
1
解决办法
2661
查看次数

非异步执行路径能否以“异步”方法返回同步结果

考虑以下方法:

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)

c# asynchronous task async-await

2
推荐指数
1
解决办法
60
查看次数

标签 统计

angularjs ×1

async-await ×1

asynchronous ×1

c# ×1

express ×1

forms ×1

node.js ×1

post ×1

task ×1