简体   繁体   中英

How to send array from html to node.js and then to mongodb?

Need to send values of long and lat as one array in input, then save it in the database. Found a lot of examples that explain how to handle arrays, but most of them are in PHP. Here's the code:

HTML

<html>
<head>
    <script>
        function geoFindMe() {
            var coordinates = document.getElementById("coordinates");
            if (!navigator.geolocation) {
                alert("Geolocation is not supported by your browser");
                return;
            }
            function success(position) {
                var latitude  = position.coords.latitude;
                var longitude = position.coords.longitude;
                var coordinates = [longitude, latitude];
                document.getElementById("coordinates").value = coordinates;
            }
            function error() { alert("Unable to retrieve your location"); }
            navigator.geolocation.getCurrentPosition(success, error);
        }
    </script>
</head>
<body>   
    <label for="pos">Allow location service</label>
    <input name="pos" id="coordinates" type="checkbox" onclick="geoFindMe()" value="coordinates[]">
</body>
</html>

app.js

app.post("/", (req, res) => {
    const newUser = new data({
        geometry: {
            type:'Point',
            coordinates: req.body.coordinates
        }
    });
});

data.js

const FindMyLocation = new Schema({
    geometry: {
        type: {
            type: String,
            default: 'Point'
        },
        coordinates: {
            type:[Number],
            index: '2dsphere'
        }
    }
});

Thanks for your attention.

Using Ajax to call the API to send the request.

<script>
        function geoFindMe() {
            var coordinates = document.getElementById("coordinates");
            if (!navigator.geolocation) {
                alert("Geolocation is not supported by your browser");
                return;
            }
            function success(position) {
                var latitude  = position.coords.latitude;
                var longitude = position.coords.longitude;
                var coordinates = [longitude, latitude];
                document.getElementById("coordinates").value = coordinates;
                var xhttp = new XMLHttpRequest();
                xhttp.open("POST",URL, true);
                xhttp.setRequestHeader('Content-type','application/json; charset=utf-8');
                xhttp.send(JSON.stringify({"coordinates":coordinates}));
            }
            function error() { alert("Unable to retrieve your location"); }
            navigator.geolocation.getCurrentPosition(success, error);
        }
    </script>

in your api you will need mongoose or mongodb package for insertion

var data = require('data.js');
app.post("/", (req, res) => {
    const newUser = new data({
        geometry: {
            type:'Point',
            coordinates: req.body.coordinates
        }
    });
newUser.save(err => {
if (err) return res.status(500).send(err);
return res.status(200).send("your success message");
});

In your data.js you will be needing at the end of file so that it could be acessible.

module.exports = mongoose.model('FindMyLocation', FindMyLocation );

To send the form data, add a jQuery Ajax call in your HTML script:

function geoFindMe() {
    // get input's value
    var coordinates = document.getElementById("coordinates").value;
    // post coordinates to "/"
    $.ajax({
        type: "POST",
        url: "/",
        data: coordinates,
        success: function() {
            // do things if successful
        }
    });
}

To get HTML form data in Express, you need to use the body-parser middleware. Additionally, the object property name you access the data through is based on the name attribute of the HTML input, not the id .

const bodyParser = require('body-parser');
app.use(bodyParser.json());

app.post("/", (req, res) => {
    const newUser = new data({
        geometry: {
            type:'Point',
            coordinates: req.body.pos
            // property is "pos" because form input name is "pos"
        }
    });
});

And then to insert the data into MongoDB through Mongoose, you would do something like this:

newUser.save().then(() => console.log('user saved'));

You can use jquery ajax as it's been used widely on browsers for API call. This sends data from browser to server.

this is part of javaScript only so don't get confused.

Will be using inline script and only additional code that you need.

On seting value of input like <input value ="coordinates[]"> You are not setting any array as value it's just a string. Like var a = "coordinates[]"; a is not an array just a string.

HTML and JS:

<body>
    <label for="pos">Allow location service</label>
    <input name="pos" id="coordinates" type="checkbox" onclick="geoFindMe()">
    <p onClick="sendCoordinatesToNode()">Click Here to Send Coordinates To NodeJs</p>

</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
    function sendCoordinatesToNode() {
        var coordinates = $('#coordinates').val();

        $.ajax({
            "url": "http://localhost:4000/", // this is url path of your API or just "/"
            "method": "POST",
            "data": {coordinates}
            // Feel free to set headers if needed, like content-type: application/json
        })
        // If API returned success then here
        .then( result => {
            // Message to notify success submition
            alert("Successfully added user.");
            return;
        })
        // If API returned error then here
        .catch ( err => {
            // Notify in case some error occurred
            alert("An error occurred.");
            return;
        });
    }
</script>

Now you will be able to get coordinates at req.body.coordinates ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM