如何发送选定复选框的数组数据以在node.js中建模

时间:2019-06-22 09:43:25

标签: node.js ajax mongodb

我想将所选复选框的值从表单发送到node.js中的对象模型

我在数组中具有复选框的值。现在我不知道如何将其发送到模型。我可以发送其他值,但是我对如何通过数组发送感到困惑

node.js中的模型类:

Model class in node.js

Ajax数据准备

Ajax data preparation

我想在模型中将departments[]的值从ajax转换为hosDepartments

API

Response i am getting

Sending data to api

1 个答案:

答案 0 :(得分:0)

我不确定您是否已经有一个Webapi与客户端通信, 如果是,则只需使用fetchapi将数据作为json主体发送到您的api,然后从那里将其解析为模型。

fetch('yourUrlOfTheServer.tld:yourPort/yourEndpoint', {
    method: 'POST',
    headers: {'Content-Type':'application/json'},
    body: JSON.stringify(hospitalData)
});

如果没有,请使用expressjs像这样

var express = require('express') //Express Js
var bodyParser = require('body-parser') //You need a body parser to get the body sent by the client

const app = express(); //init express

app.post('/insert', bodyParser.json(), function(req, res) {
    //You can get the Bodydata you have send via req.body.hosName
    var x = new hostpitalschema;
    x.hosName = req.body.hosName;
    x.hosDetails = req.body.hosDetails;
    [...]
    //You could probably also use forEach, but I believe this is better performancewise.

    //insert d into db, or whatever your gonna do woth it
})

app.listen(6969, function() {
   console.log(`App is listening on Port 6969`)
})

您会像这样从客户端发送请求

fetch('yourUrlOfTheServer.tld:6969/insert', {
    method: 'POST',
    headers: {'Content-Type':'application/json'},
    body: JSON.stringify(hospitalData)
});