Vue的post提交请求和get提交请求的实现

因为Vue版本现在升级的越来越快啦,所以主要改变在webpack.dev.conf.js操作:
具体改变如下

post提交实现

1、将webpack.dev.conf.js替换为以下代码:

'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
var express = require('express')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,

  // these devServer
   options should be customized in /config/index.js
  devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll,
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

var apiServer = express()
var bodyParser = require('body-parser')
apiServer.use(bodyParser.urlencoded({ extended: true }))
apiServer.use(bodyParser.json())
var apiRouter = express.Router()
var fs = require('fs')
apiRouter.get('/',function(req,res){
    res.json({message:"hooray!welcome to your api!"})
});
apiRouter.route('/:apiName')
.all(function(req,res){
  fs.readFile('./db.json','utf8',function(err,data){
    if(err) throw err 
    var data=JSON.parse(data)
    if(data[req.params.apiName]){
      res.json(data[req.params.apiName])
    }
    else{
      res.send("NO SUCH API NAME")
    }
  })
})
apiServer.use('/api',apiRouter)

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port
      
      apiServer.listen(port+1,function(err){
          if(err){
            console.log(err)
            return
          }
          console.log('Listening at http://localhost:' + (port + 1) + '\n')
      })

      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})

如果你的电脑有比较器的话发现,我们只是在原有生成的类上面增加了几段代码:
增加的代码如下:

var express = require('express')
var apiServer = express()
var bodyParser = require('body-parser')
apiServer.use(bodyParser.urlencoded({ extended: true }))
apiServer.use(bodyParser.json())
var apiRouter = express.Router()
var fs = require('fs')
apiRouter.get('/',function(req,res){
    res.json({message:"hooray!welcome to your api!"})
});
apiRouter.route('/:apiName')
.all(function(req,res){
  fs.readFile('./db.json','utf8',function(err,data){
    if(err) throw err 
    var data=JSON.parse(data)
    if(data[req.params.apiName]){
      res.json(data[req.params.apiName])
    }
    else{
      res.send("NO SUCH API NAME")
    }
  })
})
apiServer.use('/api',apiRouter)
 port里面:    
 apiServer.listen(port+1,function(err){
          if(err){
            console.log(err)
            return
          }
          console.log('Listening at http://localhost:' + (port + 1) + '\n')
      })

2、找到config下面的index.js

将(大约在13行)

 proxyTable{
  }

改为:

  proxyTable: { 
      '/api': 'http://localhost:8083'
  },

好啦,以上就是post提交啦,那面我们来验证一下哦

3、 找到一个你需要用到ajaxPost提交的.vue文件

在export default里面运用post提交:
(1)在db.json里面有一段json串getList

{ 
  "getList": [
    {
      "id": 1,
      "title": "title1"
    },
    {
      "id": 2,
      "title": "title2"
    }
  ]
}

(2)在需要获取这段json串的地方使用ajax请求,请求方式为post

export default {
    created: function () {
    this.$http.post('api/getList')    //post提交的时候也可以使用get,但是get提交只能用get哦
    .then((res) => {
      this.nowList = res.data    //将json串的数据取出来赋值给某个组件
    }, (err) => {
      console.log(err)
    })
  }
  },

-----------------------------------------------------------------------------------

get提交实现

1、将webpack.dev.conf.js添加以下代码:

var jsonServer=require('json-server')
var apiServer=jsonServer.create()
var apiRouter=jsonServer.router('db.json')
var middlewares=jsonServer.defaults()

apiServer.use(middlewares)
apiServer.use('/api',apiRouter)

//这面这段代码需要添加在
//
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
//
//这段代码的下面,因为这时候才有port参数

apiServer.listen(port+1,function(){
    console.log('JSON Server is running')
})

2、修改config\index.js

将(大约在13行)

 proxyTable{
  }

改为:

proxyTable: {
  '/api': 'http://localhost:8081/#/'
},

调用

   export default {
      created: function() {
          this.$http.get('api/getList')
          .then((res)=>{
             this.nowList=res.data
          },(err)=>{
             console.log(err)
          })
      },

好啦,以上就是完整的post和get提交过程,希望可以帮到你们,博主在这里祝愿你们早日解决问题哦~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值