vue ajax post请求,Vue的post提交请求和get提交请求的实现

由于Vue版本如今升级的愈来愈快啦,因此主要改变在webpack.dev.conf.js操做:

具体改变以下css

post提交实现

一、将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)

}

})

})

若是你的电脑有比较器的话发现,咱们只是在原有生成的类上面增长了几段代码:

增长的代码以下:html

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')

})

二、找到config下面的index.js

将(大约在13行)vue

proxyTable{

}

改成:webpack

proxyTable: {

'/api': 'http://localhost:8083'

},

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

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

在export default里面运用post提交:

(1)在db.json里面有一段json串getListgithub

{

"getList": [

{

"id": 1,

"title": "title1"

},

{

"id": 2,

"title": "title2"

}

]

}

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

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提交实现

一、将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')

})

二、修改config\index.js

将(大约在13行)ajax

proxyTable{

}

改成:express

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提交过程,但愿能够帮到大家,博主在这里祝愿大家早日解决问题哦~json

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue是一种流行的JavaScript框架,用于构建用户界面。采用了组化的开发方式,使得前端发更加模块化和可维护。而Ajax是一种用于在后台与服务器进行异步信的技术,可以在不刷新整页面的情况下更新部分页面内容。 在VueAjax请求可以通过使用Vue的内置方法或者第三方库来实现Vue内置了一个名为`axios`的库,它是一个基于Promise的HTTP客户端,可以用于发送Ajax请求。 以下是使用axios发送Ajax请求的基本步骤: 1. 首先,在你的项目中安装axios库。可以使用npm或者yarn命令进行安装:`npm install axios`或者`yarn add axios`。 2. 在需要发送Ajax请求的组件中,引入axios库:`import axios from 'axios'`。 3. 使用axios发送请求,可以通过调用axios的各种方法(如get、post等)来发送不同类型的请求。例如,发送一个GET请求可以使用`axios.get(url)`方法。 4. 处理请求的响应,axios返回的是一个Promise对象,你可以使用`.then()`方法来处理成功的响应,使用`.catch()`方法来处理错误的响应。 下面是一个简单的示例代码,演示了如何在Vue中使用axios发送GET请求: ```javascript import axios from 'axios'; export default { methods: { fetchData() { axios.get('https://api.example.com/data') .then(response => { // 处理成功的响应 console.log(response.data); }) .catch(error => { // 处理错误的响应 console.error(error); }); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值