【问题标题】:why my fetch post is not working it is not responding?为什么我的获取帖子不起作用它没有响应?
【发布时间】:2020-09-06 12:42:57
【问题描述】:
addwordform.addEventListener('submit', (event)=>{
  event.preventDefault();
    const formdata=new FormData(addwordform);
    const word=formdata.get('addword');
    const description =formdata.get('addiscription');
    const worddata={
        word,description,totalcount
    };
  console.log(worddata);
  fetch(API_URL,{
      method:'POST',
      headers:{
          'content-Type':'application/json'
      },
      body:JSON.stringify(worddata),
  }).then(response=>response.json()).then( data =>{
     console.log(data);
       });
});

这是客户端的javascript 这里 API_URL="http://localhost:3005/word" 服务器端代码是

const express= require('express');
const serveStatic = require('serve-static');
const datastore=  require('nedb');
const app= express();
app.listen(3005,()=>{console.log("listening on :http://localhost:3005")});
app.use(serveStatic('public',{'index':['client.html']}));
const database=new datastore('database.db');
database.loadDatabase();
app.post('/word',(req,res)=>{
   const data=req.body;
   database.insert(data);
   res.json();
});

我正在为客户端使用 express 节点框架和 vanilla javascript,我想要的只是从具有 id=addwordform 的表单发布数据,并且我在节点中使用 nedb 轻量级数据库管理 .problem 是我从客户端发送的 worddata 没有进入服务器端“req”,所以我不能将它保存在数据库中,最终我不能“res”回来?

【问题讨论】:

    标签: javascript node.js database express nedb


    【解决方案1】:

    如果您使用的是快速版本 >= 4.16。正文解析器与 express 捆绑在一起。

    它使用 JSON 有效负载解析传入的请求,并且基于 body-parser。

    不需要使用body-parser。 Here is the documentation

    您只需在需要您的路线之前添加此代码。

    app.use(express.json()); 
    

    这里是stackoverflow original post。

    这里是express release

    这里是express commit

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 2018-03-03
      • 2020-05-27
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 2019-05-18
      • 2021-12-31
      相关资源
      最近更新 更多