【问题标题】:How to create an endpoint to axios POST如何创建一个端点到 axios POST
【发布时间】:2019-08-08 13:15:23
【问题描述】:

我目前正在构建一个类似 Twitter 的应用程序作为 Vue.js 中的编码培训,并且遇到了错误 POST 404 Not Found

当我尝试发布新推文时发生错误,而“显示以前的推文”功能有效。我使用axios post 表示“发布新推文”,axios get 用于“显示以前的推文”。我为postget 使用相同的地址http://localhost:8080/feed.json

这意味着地址本身是正确的,而就在几分钟前,我了解到 POST 的错误很可能是因为我没有为 POST 创建端点。

现在又出现了另一个问题。即使在谷歌搜索寻找一些有用的具体示例之后,我也没有很好地了解“创建端点”的样子。

所以我想通过提出以下问题来收集一些具体信息。

  • 如果我想在 Vue.js 中将端点用于 axios,我应该在哪种文件中定义端点? vue 文件? JavaScript 文件?还是其他类型的文件?
  • 在哪里定义端点?在我的主要App.vue 所在的目录中存在吗?或者别的地方?

  • “为axios post 创建端点在实际代码中的表现如何?

  • 一旦定义了端点,我应该如何使用它?我的意思是,我使用axios post 的文件如何识别它?例如,在 Vue.js 中,在 Vue 文件的 JavaScript 部分中写入行 import ShowPreviousTweets from './components/ShowPreviousTweets' 可以让您使用外部定义的 ShowPreviousTweets 组件。当您想使用外部定义的端点时,是否有与此相对应的东西?

注意:如果您通过“回答这个问题”而不是仅仅在评论部分写一些句子来回答我的问题,我非常感谢您。请务必在说明中包含一些示例代码。

[更新]

在这个程序中,服务器端由 Node.js 负责

[我的工作目录“slutuppgift”的样子]

slutuppgift/
|--                         Static files
|-- index.html              HTML-code 
|-- feed.json               the API JSON-data
|-- node_modules            
|-- src/                
|-- |-- main.js             JavaScript-code to initialize Vue & app.vue
|-- |-- App.vue             Vue-code for the application
|-- |-- components/         Vue-code for components
|-- |-- views/              Vue-code for pages/templates (Vue-router).
|-- |-- router.js           JavaScript-code for Vue-router (URL-structure)
|-- |-- api.js              JavaScript-code for Express.js (the API)

[更新版本 2]

[endpoint.js(在“后端”文件夹中]

var express = require('express');
var endpoint = express();
var portNo = 8080;

endpoint.listen(portNo, function(){
    console.log('Listening on port ' + portNo);
});

// Get method route
endpoint.get('/newKweet', function(req, res){
    res.send('GET request to kweet');
});

// POST method route
endpoint.post('/newKweet', function(req, res){
    res.send('POST request kweet');
})

[更新版本 3]

[App.vue]

newKweet(){
  var self = this;
  alert(self.kweetInput);

  this.axios.post('/newKweet', {     
    userJSON: self.userJSON
    avatar: self.userJSON.avatar,
    username: self.userJSON.username,
    handle: self.userJSON.handle,
    timestamp: self.userJSON.timestamp,
    content: self.userJSON.content,
    media: {
      type: self.userJSON.media.type,
      url: self.userJSON.media.url
    },
    actions: {
      replies: self.userJSON.actions.replies,
      rekweets: self.userJSON.actions.rekweets,
      likes: self.userJSON.actions.likes
    }  
  })
  .then(function(response){
    console.log('The output: ');
    console.log(response.data);
  })
  .catch(function(error){
    console.log('An error occured...');
    console.log(error);
  });    

  self.kweetInput = '';
  console.log('The end of newKweet() method');
}

[更新版本 4]

[App.vue的模板部分]

<template>
    <form class = "userContainer">
        <div class = "user-avatar"> 
            <img src="avatar/avatar-loggedin.jpg">
        </div>
        <textarea rows = "10" cols = "80" v-model="kweetInput">  </textarea>  
    button class = "kwitterBtn" type = "submit" @click.prevent="newKweet()">Kwitter</button>
    </form>  
</template>

[更新版本 5]

slutuppgift/
|--                         Static files
|-- index.html              HTML-code 
|-- feed.json               the API JSON-data
|-- node_modules   
|-- backend
|-- |-- endpoint.js         newly created endpoint according to the advice         
|-- src/                
|-- |-- main.js             JavaScript-code to initialize Vue & app.vue
|-- |-- App.vue             Vue-code for the application
|-- |-- components/         Vue-code for components
|-- |-- views/              Vue-code for pages/templates (Vue-router).
|-- |-- router.js           JavaScript-code for Vue-router (URL-structure)
|-- |-- api.js              JavaScript-code for Express.js (the API)

[endpoint.js]

var express = require('express');
var endpoint = express();

var cors = require('cors');
endpoint.use(cors());

var portNo = 3000;

endpoint.listen(portNo, function(){
    console.log('Listening on port ' + portNo);
});

// Get method route
endpoint.get('/newKweet', function(req, res){
    res.send('GET request to kweet');
});

// POST method route
endpoint.post('/newKweet', function(req, res){
    res.send('POST request kweet');
})

【问题讨论】:

  • 你有一个服务器正在运行,提供 json 文件吗?
  • vue 是一个前端框架。当您执行 HTTP 请求(例如使用 axios)时,该请求会发送到后端,例如 php 服务器。然后,此后端可以接受特定 URL 上的 http 方法(例如 POSTGET)。
  • 正如更新后的帖子一样,我在服务器端使用 Node.js。
  • 看看json-server。它不是生产就绪的,但是为了学习如何构建前端,它会在你的 JSON 数据文件上提供一个 REST API。

标签: vue.js axios endpoint


【解决方案1】:

在您的主节点应用程序 js(在后端)中安装并运行 express: (使用 npm install --save express 安装)

var express = require('express');
var app = express();

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

然后以这种方式创建所有端点

// GET method route
app.get('/tweet', function (req, res) {
  res.send('GET request to tweet');
});

// POST method route
app.post('/tweet', function (req, res) {
  res.send('POST request tweet');
});

如果你有不同的方法,你可以使用相同的端点,但你不能有两个端点具有相同的方法和端点。


更新

让我们在这里看看:https://repl.it/repls/GargantuanFaintSets

这是一个基本的在线应用程序,我为您展示 express 和 node 如何协同工作。该应用程序创建一个临时网站,现在点击以下链接: - https://gargantuanfaintsets--five-nine.repl.co(家,“/”获取端点) - https://gargantuanfaintsets--five-nine.repl.co/tweet(“/tweet”获取端点) - 对于您需要使用 axios 或表单的帖子,因为直接使用浏览器导航总是会得到调用

现在在您的本地机器上,如果您的应用程序设置正确并且您的终端已启动并运行命令node app.js(请确保使用您的 .js 主文件的名称并从后端文件夹运行命令)你可以导航到这个链接:http://localhost:3000/tweet

【讨论】:

    【解决方案2】:

    要启用跨域请求,请执行以下操作:

    从终端安装cors(您需要留在节点应用程序的根文件夹中):

    npm install --save cors
    

    然后在您的应用程序主 js 中,在实际模块导入之后添加这一行

    var express = require('express')
    var app = express()
    /* THE NEW PART */
    var cors = require('cors')
    app.use(cors())
    /* ... */
    

    然后用 axios 重试调用端点

    【讨论】:

    • 仍然得到同样的错误。而这次我还得到了xhr.js?ec6c:172 POST localhost:3000/newKweet net::ERR_FAILED,我添加了更新的版本5,以显示endpoint.js文件的当前状态。
    • 我在线创建了您的应用程序的副本:repl.it/repls/CrowdedRespectfulDegree 尝试调用此端点:crowdedrespectfuldegree--five-nine.repl.co/newKweet
    • 这个副本有什么作用?当我点击“运行”按钮时,它会产生很多绿色语句作为输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多