我有一个简单的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>
当我点击按钮时,出现以下错误:
XMLHttpRequest无法加载localhost:8090。跨源请求仅支持协议方案:http,data,chrome,chrome-extension,https,chrome-extension-resource。
当我尝试调用另一个服务器,比如google.com时,出现以下错误:
build.js:19188 GET http://localhost:8080/google.com 404(未找到)
因此,似乎Vue将localhost:8080放在调用前面,这可能是我的问题所在?对于我来说,进行服务器调用是完全新的,我只是在使用Vue并在学习Node.js。