用Vue.js调用一个Node.js服务器

我有一个简单的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); }); 

我可以从命令行使用curl来调用这个服务器:

 $curl localhost:8090 

但是,当我尝试从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 } }) 

这是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> 

当我点击button,我得到这个错误:

XMLHttpRequest无法加载localhost:8090。 协议scheme仅支持跨源请求:http,data,chrome,chrome-extension,https,chrome-extension-resource。

当我尝试调用其他服务器时,如google.com,我得到这个错误:

build.js:19188 GET http:// localhost:8080 / google.com 404(Not Found)

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

这基本上与Node或Vue无关,一切都与浏览器的安全性如何实现有关。 CORS不是解决方法。 阅读CORS,看看为什么需要它 。 我的这个问题和你的问题很相似,在答案部分也有一些很好的信息。 为了能够在不使用CORS的情况下调用API,它需要在相同的主机,端口和协议上运行,否则将被浏览器阻止。

多年前,在CORS出现之前,您需要使用JSONP来实现这一点。 你当然可以看看它是如何工作的,但是现在对这种技术的需求非常less,因为我们有适当的CORSforms的跨域支持。

在关于“在使用Vue.js时人们如何调用API”的注释部分之一中提到您的问题时,他们执行以下操作之一:

  1. 在另一个服务器(如api.mydomain.com )上运行API,但在响应中设置CORS头。
  2. 如上所述,但是客户端和服务器使用上述的JSONP方法来包装响应。
  3. 在与一个服务页面相同的服务器上运行API。 这意味着API调用将针对诸如localhost:8080/api的端点完成
  4. 扭转#3:只是代理服务器进入服务器到另一台服务器。 意思是你可以让你的api服务器在其他地方运行,但是接受/api调用的主服务器只会在去除/api前缀后在下一个服务器上发送这些请求。 通常,人们在你的应用服务器前面设置一个Apache或者Nginx实例,并且在那里做实际的代理,但是你也可以在你的应用服务器中使用类似node-proxy的方法来实现 。

你可能已经可以通过这行来阅读,但是省去一些麻烦(和时间),只需使用CORS 🙂 @trquoccuong在他的回答中有详细的说明。

CORS的问题,可以使用cors节点模块或添加请求头

如果使用Express

 res.header('Access-Control-Allow-Origin', 'http://localhost:8080'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With'); 

如果使用http模块

 res.setHeader