使用Vue.js调用Node.js服务器

Ara*_*idi 4 javascript http node.js vue.js server

我有一个简单的Node.js服务器启动并运行.这是代码:

var http = require('http');
var server = http.createServer();
server.on('request', function(req, res) {
    res.writeHead(200, {
        'content-type': 'text/plain'
    });
    res.write('Hello World!');
    res.end();
})

server.listen(8090);
server.once('listening', function() {
    console.log('Hello World server listening on port %d', 8090);
});
Run Code Online (Sandbox Code Playgroud)

我可以使用命令行中的curl来调用此服务器:

$curl localhost:8090
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试从Vue应用程序调用它时,我收到错误.我有一个在localhost:8080上运行的Vue应用程序,我想调用我的localhost:8090服务器.我的main.js Vue文件是这样的:

import Vue from 'vue'
import resources from 'vue-resource'
Vue.use(resources)

import App from './components/App.vue'

import style from './styles/main.scss'

/**
 * Root Vue instance
 * @param {[element]} el: 'body' [Adds to the html body]
 * @param {[component]} components: {app: App} [Renders ./component/App]
 */
new Vue({
  el: 'body',
  components: {
    app: App
  }
})
Run Code Online (Sandbox Code Playgroud)

这是App组件:

<template>

<h1>{{ msg }}</h1>

<input v-model="msg">
<button v-on:click="get">Call Server</button>

</template>

<script>

export default {
    data: function() {
        return {
            msg: 'Hello World!'
        }
    },
    methods: {
        get: function() {
            // GET request
            this.$http({
                url: 'localhost:8090',
                method: 'GET'
            }).then(function(response) {
                console.log('ok');
            }, function(response) {
                console.log('failed');
            });
        }
    }
}

</script>
Run Code Online (Sandbox Code Playgroud)

当我单击按钮时出现此错误:

XMLHttpRequest无法加载localhost:8090.交叉源请求仅支持协议方案:http,data,chrome,chrome-extension,https,chrome-extension-resource.

当我尝试拨打另一台服务器时,例如google.com,我收到此错误:

build.js:19188获取http:// localhost:8080/google.com 404(未找到)

所以看起来Vue正在把localhost:8080放在电话前面,也许这就是我的问题所在?进行服务器调用对我来说是全新的,我只是在玩Vue并想在我这样做时学习Node.js.

oli*_*ren 6

这基本上与Node或Vue无关,而且与浏览器的安全性如何实现有关.CORS不是一种解决方法.阅读CORS以了解它的原因.我的这个问题与你的问题非常相似,在答案部分也有一些很好的信息.为了能够调用的API不使用它需要在同一台主机,端口和协议上运行CORS,否则会被你的浏览器被阻塞.

多年前,在CORS出现之前,你需要使用JSONP来实现同样的目标.你当然可以看一下它是如何工作的,但是现在很少需要这种技术,因为我们以CORS的形式提供了适当的跨域支持.

关于您在"使用Vue.js时人们如何调用API?"的评论部分中的问题,他们会执行以下操作之一:

  1. 在另一台服务器(例如api.mydomain.com)上运行API ,但在响应上设置CORS头.
  2. 如上所述,但客户端和服务器使用上面提到的JSONP方法包装响应.
  3. 在与服务页面相同的服务器上运行API.这意味着将对诸如的端点进行api调用localhost:8080/api
  4. 扭转#3:只是将服务器上的代理呼叫转移到另一台服务器.这意味着您可以让api服务器在其他地方运行,但是接受调用的主服务器 /api将在剥离/api前缀后在下一个服务器上发送这些请求.通常,人们要么在应用服务器前面设置一个Apache或Nginx实例,并在其上进行实际代理,但你也可以在app服务器中使用node-proxy之类的东西.

你可能已经通过这些行阅读了这个,但是省去了一些麻烦(和时间)并且只使用CORS :) @trquoccuong在他的回答中有详细说明.