将数据从客户端传递到服务器

时间:2019-03-29 18:05:06

标签: javascript express fetch

在我的代码中,我要将ID从客户端传递到服务器。 我正在尝试使用获取将Content-Type设置为Application / json的方法,但是看起来我们遇到了一些问题(我分析了请求,但它没有创建主体)。 是否有一种简单的方法将数据从客户端传递到服务器?

{#each accounts}}
    <form action="/users/chat" method="POST">
      <div class="form-group">
        <p>{{@index}}</p>
        <label for="name" value={{username}}>{{username}}</label>
      </div>
      <div class="form-group">
        <label for="name">{{email}}</label>
      </div>
      <button class="myButton" id="{{@index}}">chat</button>
      </form>

    {{else}}
    <p>No account</p>
    {{/each}}


<script>

  const buttons = document.getElementsByClassName('myButton');
  for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click',  function(e) {
      let ident=this.id;
      console.log(ident);
      console.log('button was clicked');
   fetch("/myurl",{
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    method: "POST",
    body: JSON.stringify({id : ident})
})    
}



</script>


2 个答案:

答案 0 :(得分:0)

这是服务器的代码:

var express = require('express');
var router = express.Router();
var app = express();
var bcrypt = require('bcryptjs');
const db = require('../config/database');
const Account = require('../models/Account');
const chat = require('../models/chat');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
var passport = require('passport');
LocalStrategy = require('passport-local').Strategy;
const {ensureAuthenticated}=require('../config/auth');
app.use(express.urlencoded());
app.use(express.json());

//Socket
const PORTS = process.env.PORT || 7001;
var client = require('socket.io').listen((PORTS, console.log`SOCKET started on port ${PORTS}`)).sockets;

var password;
var username;
var accounts;

//Register
router.get('/register', function(req,res){
    res.render('register');
});

//CHAT
router.get('/chat', ensureAuthenticated, (req,res)=>{
    console.log(request.body.user.id);
    res.render('chat');
});
    module.exports=router;

答案 1 :(得分:0)

经过仔细检查,您在客户请求中的此行是fetch("/myurl",{ ...

的原因

如果您在MDN看到该指南,则用法为fetch('http://example.com/movies.json')Fetch API期望完整的url/uri以及协议(http, https)等。

因此您的请求应类似于:

fetch("http://yourdomain.com", { ...