使用数据从nodejs向php Api发布请求

用户206904

我在example.com/api.php上运行了一些api

为了将 api 与 ajax 一起使用,我使用以下代码:

        $.ajax({
            url: 'https://example.com/api.php',
            method: 'post',
            data: {'pass': 'mypass', 'action': 'someaction'},
        }).done(function(results){
            //results = JSON.parse(results); //no need to parse it!
            console.log(results);

            });
        })

我试图用 node.js 实现同样的事情,但我不知道如何发送数据。

我尝试了很多方法,这是其中之一:

axios.post('https://example.com/api.php', {
    'pass': 'passs',
    'action': 'myaction'
})
.then((res) => {
  console.log(`statusCode: ${res.statusCode}`)
  console.log(res)
  console.log(`statusCode: ${res.data}`)
})
.catch((error) => {
  console.error(error)
})

但我根本无法让它工作!res.statusCode 返回 undefined 而 res.data 根本不返回任何内容。服务器记录每个用户尝试通过 api 执行的操作。php api 有这样的东西:

    if($_POST['pass']== thePassword && $_POST['action']=='aSpecifiAction'){
// log the action,
//execute the action
}

我的操作没有出现在日志中,这意味着我的 axios 代码没有向 api 发送任何数据。那么如何让它表现得像上面的 jquery 代码呢?

使用 axios 不是必须的,如果有更简单的请求或任何其他模块的解决方案,那就没问题了。

提前致谢

用户206904

有人在github上帮我找到了问题。问题是“jQuery 默认对 POST 数据使用 application/x-www-form-urlencoded 格式,而 axios 默认使用 JSON”

在这个链接中,他们详细解释了https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format

解决方案 :

const axios = require('axios')

const qs = require('qs');
axios.post('https://example.com/api.php',  qs.stringify({
    'pass': 'passs',
    'action': 'myaction'
}))
.then((res) => {
  console.log(`statusCode: ${res.statusCode}`)
  console.log(res)
  console.log(`statusCode: ${res.data}`)
})
.catch((error) => {
  console.error(error)
})

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

向被 CORS 政策阻止的 API 发布请求

如何使用 nodejs 10x 向 aws lambda 中的外部 api 发送发布请求?

如何使用JSON数据获取API发布请求

使用 Python 请求将数据发布到 REST API

向Openhab2和Swift发布API请求

NodeJS请求模块Google Maps GeoCode API发布

api端点上的发布请求不返回数据

向外部API发送发布请求并提取数据

如何使用FileUpload向Azure AD受保护的REST API进行REST API发布请求

如何使用 POSTMAN api 工具在 Moodle 上发布请求

如何使用AWS的HTTP API执行发布请求?

使用API密钥的Guzzle发布导致400错误请求

使用Python请求模块将文件发布到API

使用Active Collab API在单个请求中发布多个文件:

无法通过 Amadeus API 使用 guzzle 发布请求

如何在php-codeigniter中向RESTserver api发送发布请求?

Volley,ngrok-无法使用Volley向ngrok REST API发出发布请求

从 Ajax 请求向 PHP 发布多个值

如何使用BitBucket REST api 2.0发布请求请求注释?

使用请求和current.futures异步发送多个API发布请求

使用请求模块发布表单数据 - Nodejs & Express

用PHP发布请求

使用Wget发布请求?

使用ReactJS发布请求

使用节点的请求承诺将数据发布到JSON REST API

C# 如何通过 Facebook API 使用多个 POST 请求发布数据

.NET Core将本地API表单数据发布请求转发到远程API

NodeJS发布请求“无法发布/上传”

ECONNRREFUSED 使用 Nodejs 向 API 发出获取请求时出错