方法一:
https://www.thepolyglotdeveloper.com/2017/10/consume-api-data-http-vuejs-web-application/
后端服务器创建restful api,让vue来获取数据。建议使用 vue-resource 方式。
Getting Started with a New Vue.js Project
For simplicity, we’re going to create a fresh Vue.js project and integrate each of the axios and vue-resource libraries into it. Assuming you’ve got the Vue CLI installed, execute the following:
vue init webpack http-project
When prompted, fill in the project information. It does not matter if you choose standalone (runtime and compiler) project vs the runtime-only project. Just say no to all the testing features and the routing. This is a very bare bones project that we’re going to work with.
After the project has been created, execute the following:
cd http-project npm install
At this point we should be ready to start development.
Make HTTP Requests to Remote Web Services with axios
One of the more popular HTTP libraries out there is called axios. It is dead simple and very lightweight, which makes it a great solution for any Vue.js project.
To include axios in your project, execute the following:
npm install axios --save
Going forward, all our development will happen in the src/components/HelloWorld.vue file that was included when we scaffolded the project with the Vue CLI.
Without getting too far ahead of ourselves, open the project’s src/components/HelloWorld.vue file and include the following:
<template> <div class="hello"> <h1>Your IP is {{ ip }}</h1> <input type="text" v-model="input.firstname" placeholder="First Name" /> <input type="text" v-model="input.lastname" placeholder="Last Name" /> <button>Send</button> <br /> <br /> <textarea>{{ response }}</textarea> </div> </template> <script> import axios from "axios"; export default { name: 'HelloWorld', data () { return { ip: "", input: { firstname: "", lastname: "" }, response: "" } }, mounted() { }, methods: { } } </script> <style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } textarea { 600px; height: 200px; } </style>
In the above code, notice that we’ve initialized a few variables in the data
method of the <script>
tags. These variables are bound to components found in the <template>
. For example, the ip
variable will be printed, the input
object will have a two-way data binding with our form, and the response
variable will be printed.
Within the <script>
tag you’ll also notice the following:
import axios from "axios";
This is all it takes to start using the axios library in our code.
Rather than creating our own set of RESTful APIs, let’s go ahead and leverage one that is already available and designed for testing. We’re going to make use of httbin.
The first thing we do when it comes to HTTP will be obtaining our IP address when the application loads. We can send a GET request over HTTP to httpbin to find this information.
Take a look at the following JavaScript code:
<script> import axios from "axios"; export default { name: 'HelloWorld', data () { return { ip: "", input: { firstname: "", lastname: "" }, response: "" } }, mounted() { axios({ method: "GET", "url": "https://httpbin.org/ip" }).then(result => { this.ip = result.data.origin; }, error => { console.error(error); }); }, methods: { } } </script>
Using axios
we can send a request and work with a promise. If the request is successful, we will assign our ip
variable the value of our origin
IP found in the response.
Not so bad right?
Now let’s create a method for sending a POST request over HTTP based on our form information. Take a look at the following JavaScript code:
<script> import axios from "axios"; export default { name: 'HelloWorld', data () { return { ip: "", input: { firstname: "", lastname: "" }, response: "" } }, mounted() { axios({ method: "GET", "url": "https://httpbin.org/ip" }).then(result => { this.ip = result.data.origin; }, error => { console.error(error); }); }, methods: { sendData() { axios({ method: "POST", "url": "https://httpbin.org/post", "data": this.input, "headers": { "content-type": "application/json" } }).then(result => { this.response = result.data; }, error => { console.error(error); }); } } } </script>
We’ve created a sendData
method that sends the input
object as payload data. Because we’re sending an object, we need to specify via HTTP headers that the content is of JSON format.
Upon success, we set the response
variable to whatever the result is. However, we need a way to call the sendData
method. Head back into the <template>
block and change the markup to look like the following:
<template> <div class="hello"> <h1>Your IP is {{ ip }}</h1> <input type="text" v-model="input.firstname" placeholder="First Name" /> <input type="text" v-model="input.lastname" placeholder="Last Name" /> <button v-on:click="sendData()">Send</button> <br /> <br /> <textarea>{{ response }}</textarea> </div> </template>
We’ve added an v-on:click
event to the button. This will call the sendData
method and the bound form data will be used.
There are many more things that can be done with axios. To see the true power that axios offers, check out the official documentation.
Make HTTP Requests to Remote Web Services with vue-resource
The axios library isn’t the only way to make HTTP requests. The library vue-resource was once packaged into Vue.js, but was since separated into another project. This doesn’t make the project deprecated, just externally maintained.
Before we can use the vue-resource library, it must be downloaded. From the command line, execute the following:
npm install vue-resource --save
The setup to use the vue-resource library is slightly different than what we had to do for the axios library. Open the project’s src/main.js file and include the following:
import Vue from 'vue' import App from './App' import VueResource from 'vue-resource'; Vue.use(VueResource); Vue.config.productionTip = false new Vue({ el: '#app', render: h => h(App) })
Notice that we’ve imported the library and told Vue to use it. By doing this, we’ll be able to use the $http
service in Vue.js.
Head back into the project’s src/components/HelloWorld.vue file. We’re going to only alter the <script>
block. Everything that we had previously created for axios can remain the same.
<script> export default { name: 'HelloWorld', data () { return { ip: "", input: { firstname: "", lastname: "" }, response: "" } }, mounted() { this.$http.get("https://httpbin.org/ip").then(result => { this.ip = result.body.origin; }, error => { console.error(error); }); }, methods: { sendData() { this.$http.post("https://httpbin.org/post", this.input, { headers: { "content-type": "application/json" } }).then(result => { this.response = result.data; }, error => { console.error(error); }); } } } </script>
Things have only changed slightly between our vue-resource version and our axios version. Now we can call the $http.get
and $http.post
methods to do business. How we structure them is similar to the previous and likewise with the response.
For more information on what the vue-resource library can do, check out the official documentation.
Conclusion
You just saw two different ways to make HTTP requests to some remote web service within a Vue.js web application. There is no official way to use HTTP in Vue.js, so options like axios and vue-resource become very valid.
If you’re looking to create your own RESTful API to be consumed by Vue.js, check out a previous tutorial I wrote titled, Building a RESTful API with Node.js and Hapi Framework.
方法二:
vue 3.0 以后可以使用proxy作为代理,将请求定向到后端服务器。
开发的时候直接架个 node 服务器,或者 vue-cli 自带的 proxy,直接就可以跨域,根本不需要设置,然后vue 代码 build 直接生成静态文件部署,vue 和 后端server的端口不能一样。
https://stackoverflow.com/questions/40315451/proxy-requests-to-a-separate-backend-server-with-vue-cli
http://vuejs-templates.github.io/webpack/proxy.html
In @vue/cli 3.x:
- Create a
vue.config.js
file in the root folder of your project, if you don't already have one. - Have its contents as follows:
// vue.config.js module.exports = { devServer: { proxy: { "/gists": { target: "https://api.github.com", secure: false } } } };
Now any call to (assuming your dev server is at localhost:8080
) http://localhost:8080/gists
will be redirected to https://api.github.com/gists
.
Another example: proxying all calls. Say you have a local backend server that is typically deployed at localhost:5000
and you want to redirect all calls to /api/anything
to it. Use:
// vue.config.js module.exports = { devServer: { proxy: { "/api/*": { target: "http://localhost:5000", secure: false } } } };
或者:
When integrating this boilerplate with an existing backend, a common need is to access the backend API when using the dev server. To achieve that, we can run the dev server and the API backend side-by-side (or remotely), and let the dev server proxy all API requests to the actual backend.
To configure the proxy rules, edit dev.proxyTable
option in config/index.js
. The dev server is using http-proxy-middleware for proxying, so you should refer to its docs for detailed usage. But here's a simple example:
// config/index.js module.exports = { // ... dev: { proxyTable: { // proxy all requests starting with /api to jsonplaceholder '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, pathRewrite: { '^/api': '' } } } } }
The above example will proxy the request /api/posts/1
to http://jsonplaceholder.typicode.com/posts/1
.
URL Matching
In addition to static urls you can also use glob patterns to match URLs, e.g. /api/**
. See Context Matching for more details. In addition, you can provide a filter
option that can be a custom function to determine whether a request should be proxied:
proxyTable: { '**': { target: 'http://jsonplaceholder.typicode.com', filter: function (pathname, req) { return pathname.match('^/api') && req.method === 'GET' } } }
另一个例子:
//vue-cli3.0 里面的 vue.config.js做配置 devServer: { proxy: { '/rng': { //这里最好有一个 / target: 'http://45.105.124.130:8081', // 后台接口域名 ws: true, //如果要代理 websockets,配置这个参数 secure: false, // 如果是https接口,需要配置这个参数 changeOrigin: true, //是否跨域 pathRewrite:{ '^/rng':'' } } } }
下面的 pathRewrite 表示的意思是 把/rng 替换为 空,那么proxy后的请求地址就为 http://45.105.124.130:8081/xxxx/xxx(用在如果你的后端server地址没有 rng 的情况)。
方法三:
如果你用的是 express 做后端,则可以参考如下资料:
https://stackoverflow.com/questions/52229626/how-to-deploy-a-vue-js-application-on-node-js-server
Since Vue is only a frontend library, the easiest way to host it and do things like serve up assets is to create a simple Express friendly script that you can use to start a mini-web server. Read up quickly on Express if you haven’t already. After that, add express:
npm install express --save
Now add a server.js
file to your project’s root directory :
// server.js var express = require('express'); var path = require('path'); var serveStatic = require('serve-static'); app = express(); app.use(serveStatic(__dirname + "/dist")); var port = process.env.PORT || 5000; var hostname = '127.0.0.1'; app.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
after that you could run :
node server
and your project will be served at the given host and port
Assuming that you have already the dist
directory, if you don't have it run :
npm run build
in order to generate it