【问题标题】:Ajax and Vue cliAjax 和 Vue cli
【发布时间】:2020-03-16 13:48:37
【问题描述】:

我有一个 vue cli 项目,我正在尝试在我的应用程序中进行 ajax 调用,如果我在 localhost:7999 上它可以工作,但我希望它与我的应用程序在同一页面上工作,这是在本地主机:8080。我听说过 Axios,但如果有不使用 Axios 的方法,我希望我能在这里找到它。

vue.config.js

global.changement = "Johnny Depp";

var express = require('express')
var session = require('express-session')
var app = express();
var bodyParser = require('body-parser');

var userStoredInMemory = "LEBROONNN JAMES";

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/public/index.html');
});

app.get('/api/user', function (req, res) {
  res.json(changement);
});

app.post('/api/user', function (req, res) {
  // userStoredInMemory = req.body;
  // userStoredInMemory = "oui";
  res.send('User was already stored from express.');
});

app.listen(7999, function () {
  console.log('server up and running at 8080 port');
});

index.html

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
 
<script>
  
    function lebron() {
        $(document).ready(function () {
            $.ajax({
                type: 'GET',
                url: 'http://localhost:7999/api/user'
            })
            .done(function (data) {
                alert(JSON.stringify(data));
                localStorage.setItem('name',JSON.stringify(data));
            });
        });
    }

    setInterval(lebron, 1000);

</script>

<noscript>
    <strong>We're sorry but it doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
    
<div id="app"></div>
<!-- built files will be auto injected -->
 

没有输出,没有警报。

【问题讨论】:

  • 信息不足。不知道你那边出了什么问题。在正常情况下,它可能会按预期工作。你是唯一可以调试请求的人。开发工具中的网络选项卡和控制台可供您使用。您可以使用fail 来捕获错误,以防万一。 Axios 被广泛使用是因为它适合这项任务,而 jQuery 不是现代应用程序中常见的依赖项。
  • 首先,如果它们在不同的端口上运行,您就无法将 ajax 请求从客户端发送到服务器。你会遇到cors问题。你可以通过在 node 中安装 cors 包并使用它的中间件来解决它。您还可以在文件 vue.config.js 中配置以使用代理通过 express 运行服务器。看看这里cli.vuejs.org/config/#devserver-proxy
  • 为什么document.ready在函数里面?

标签: javascript jquery node.js ajax


【解决方案1】:

你应该在你的服务器中使用 cors。

const express = require('express');
const cors = require('cors');
const app = express();

app.use((req, res, next) => cors({
        origin: 'localhost:8080', // your frontend app url
        optionsSuccessStatus: 200,
        credentials: true
    })(req, res, next)
);

【讨论】:

    猜你喜欢
    • 2019-06-12
    • 2018-02-14
    • 2018-06-12
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 2020-04-21
    • 2017-12-26
    相关资源
    最近更新 更多