使用提取请求时,它始终处于待处理状态

时间:2019-09-28 15:07:48

标签: javascript node.js mongodb express

当我检查获取请求的状态时,我只会看到“待处理”。服务器什么也没回来。我认为问题出在以下几行:

mews.insert(mew).then(createdMew => {
  res.json(createdMew);
});

但是我完全按照我遵循的教程进行操作

const express = require('express');
const app = express();
const http = require('http').Server(app);
const cors = require('cors');
const monk = require('monk');
const db = monk('localhost/meower');
const mews = db.get('mews');

app.use(cors());
app.use(express.json());
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});
app.get('/style.css', (req, res) => {
  res.sendFile(__dirname + '/style.css');
});
app.post('/mews', (req, res) => {
  if (isValidMew(req.body)) {
    const mew = {
        name: req.body.name.toString(),
        content: req.body.content.toString(),
        created: new Date()
      };

    mews.insert(mew).then(createdMew => {
      res.json(createdMew);
    });
  } else {
    res.status(422);
    res.json({
      message: 'name and content are require :('
    });
  }
});
http.listen(3000, () => console.log('running on 3000'));

function isValidMew(mew) {
  return mew.name && mew.name.toString().trim() != '' &&
    mew.content && mew.content.toString().trim() != '';
}
const form = document.querySelector('form');
const loadingElement = document.querySelector('.loading');
const API_URL = 'http://localhost:3000/mews';

loadingElement.style.display = 'none';
form.addEventListener('submit', (e) => {
  e.preventDefault();

  const formData = new FormData(form);
  const name = formData.get('name');
  const content = formData.get('content');
  const mew = {
      name,
      content
    };

  form.style.display = 'none';
  loadingElement.style.display = '';
  fetch(API_URL, {
    method: 'POST',
    body: JSON.stringify(mew),
    headers: {
      'content-type': 'application/json'
    }
  }).then(response => response.json()).then(createdMew => {
    console.log(createdMew);
  });
});

0 个答案:

没有答案