Axios post保持在等待状态

3

这是在Vue中使用Axios进行简单的Post请求:

import axios from 'axios'
export default {
    name: 'HelloWorld',
    props: {
        msg: String
    },
    mounted () {
        const code = 'test'
        const url = 'http://localhost:3456/'
        axios.post(url, code, { headers: {'Content-type': 'application/x-www-form-urlencoded', } }).then(this.successHandler).catch(this.errorHandler)
    },
    methods: {
        successHandler (res) {
            console.log(res.data)
        },
        errorHandler (error) {
            console.log(error)
        }
    }
}

Get方法可以正常工作。但是在网络选项卡上,Post方法保持为“待定”。我可以确认我的Web服务中有一个Post方法,并且它返回了一些内容(在Postman上测试过)。

更新

将代码作为参数发送:

axios(url, {
    method: 'POST',
    headers: {
        'content-type': 'application/json',
    },
    params: {
        code : 'test'
    },
}).then(this.successHandler).catch(this.errorHandler)

网络服务

server.post('/', (req, res, next) => {
    const { code }  = req.params

    const options = {
        validate: 'soft',
        cheerio: {},
        juice: {},
        beautify: {},
        elements: []
    }

    heml(code, options).then(
        ({ html, metadata, errors }) => {
            res.send({metadata, html, errors})
            next()      
        })
})
2个回答

2

我认为你的axios请求结构有问题。尝试使用以下结构:

const URL = *YOUR_URL*;
axios(URL, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
    },
    data: *YOUR_PAYLOAD*,
  })
    .then(response => response.data)
    .catch(error => {
      throw error;
    });

如果您正在发送查询参数:
axios(URL, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
    },
    params: {
     code: 'your_string'
    },
  })

如果是路径变量,您可以设置您的URL:
const url = `http://localhost:3456/${code}`

如果问题仍然存在,请告诉我。

现在发生了一些事情。但是出现了一个错误:代码:"InvalidContent",消息:"无效的JSON:在位置1处的JSON中有意外的标记e"。我的网络服务期望一个名为code的参数,并且它必须是一个字符串。 - undefined
我建议您继续使用 application/json 内容类型。您应该发送 {code: 'your_string'},在服务器端您将获得一个 JSON,并且可以从请求负载中检索 'code' 键。您的 POST 请求问题已经修复,这是一个解析问题。 - undefined
好的,我会试试看。还有一个问题:我在本地运行webservice的端口是3456,vue应用的端口是8080。这样有问题吗? - undefined
1
找到了问题。我的网络服务期望代码作为参数。 - undefined
2
搞定了!在我们的网络服务中,不再使用const { code } = req.params,我改成了const { code } = req.body - undefined
显示剩余9条评论

1

我也遇到过这个问题。网络调用一直挂起,通过从server.js(路由文件)返回响应(例如res.json(1);)解决了这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接