简体   繁体   中英

how to fetch POST request body data from the client side?

Sorry for this noob question, student here and still learning

I'm trying to pass the request body of a POST request from server to client. I have an Arduino sensor making post requests with sensor data to an express server. The sensor data is inside the POST request body, and I push the data to an array called 'dataArray'. This part seems to be working.

My problem is that I'm now stuck on how to pass this data from the express server to a Vue component on the client side. Should I make a new route? I'm not asking anyone to write any code for me, I'm just hoping someone could point me in the right direction or suggest something, because I'm at a loss on exactly how I should go about doing this. Thank you.

server.js

var express = require("express")
var cors = require("cors")
var bodyParser = require("body-parser")
var app = express()
var mongoose = require("mongoose")
var Users = require("./routes/Users")
var port = process.env.PORT || 5000
var dataArray = []

app.use(bodyParser.json())
app.use(cors())
app.use(bodyParser.urlencoded({ extended: true }))

const mongoURI = 'my_connection_string'

mongoose.connect(mongoURI, { useNewUrlParser: true })
  .then(() => console.log("MongoDB Connected"))
  .catch(err => console.log(err))

app.use("/users", Users)
app.route("/api/:apikey1")


app.post("/api/:apikey1", function(request, response) {
  var myData = request.body;
  console.log(myData)
  dataArray.push(myData)
  response.send("Array Filled")
});

app.listen(port, function () {
console.log("Server is running on port: " + port)
})

Any data flow from the server to client must be first initiated on the client side, either by polling , usingWebSockets or Server-sent events .

If you want to keep it simple use the socket.io library.

It is available for both client and server, you can use in your Vue client too.

Also, you won't need any extra route, just in your app.post("/api/:apikey1") route, use the emit method on socket.io library to broadcast the data as it is received from the sensors

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