【问题标题】:vue express replace GET with POSTvue express 将 GET 替换为 POST
【发布时间】:2020-09-10 07:18:42
【问题描述】:

我用 express 和 mysql 创建了一个 Vue 应用程序。问题是我需要使用 POST 而不是 GET(目前正在工作)。

快递:

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();
 
app.use(morgan('tiny'));
app.use(cors());
app.use(bodyParser.json());

var data = result; //receive result from database
app.get('/data', (req, res) => { //send data to client
  res.writeHead(200, {'Content-Type':'application/json'});
  res.write(JSON.stringify(data));
  return res.end();
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`listening on ${port}`);
}); 

Vue 组件:

const API_URL = "http://localhost:3000/data"

export default {
  data() {
    return{
      myJson: []
    }
  },
  beforeCreate() { //receive data from the server
    fetch(API_URL)
    .then(response => response.json())
    .then(result => {
      this.myJson = result //save data in the variable
    })
  }
}

main.js

import Vue from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

我需要使用 POST,因为即使刷新后,页面也不会更新 myJson 变量。我到处寻找,没有找到路。

【问题讨论】:

    标签: express vue.js


    【解决方案1】:

    我用 axios 解决了我的问题。

    快递

    app.post('/data', (req, res) => { //here I just change get to post
      res.writeHead(200, {'Content-Type':'application/json'});
      res.write(JSON.stringify(data));
      return res.end();
    });
    

    Vue 组件

    import axios from 'axios' //I import axios after doing npm install
    
    axios.post(API_URL) //I just change fetch to axios.post
    .then(result => {
      this.myJson = result.data //Here I add .data
    })  
    

    编辑:所以我发现问题在于我在请求之外进行查询:

    var data = result; // <-----  **WRONG**
    app.post('/data', (req, res) => { //send data to client
      var data = result; // <----- **RIGHT**
      res.writeHead(200, {'Content-Type':'application/json'});
      res.write(JSON.stringify(data));
      return res.end();
    });
    

    这就是它第一次工作的原因。

    【讨论】:

      猜你喜欢
      • 2013-11-14
      • 1970-01-01
      • 2012-04-02
      • 2020-06-21
      • 2019-04-19
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多