javascript - nodejs发送数据到api axios
问题描述
下面是我的nodejs配置:
const Tail = require('tail').Tail; const axios = require("axios"); console.log("Watching..."); var tail = new Tail("./nxerror.log"); tail.watch() tail.on("line", data => { console.log("data changeed"); console.log(data); var username = 'Eve' var password = 'changeme' const body = {"action":"EventsRouter", "method":"add_event", "data": [{"summary":"test","device":"test","message":"msg","component":"testhost","severity":"5","evclasskey":"nxlog","evclass":"/nxlog/perf","monitor":"localhost"}],"type":"rpc","tid":2} var url = 'https://myurl.com/zport/dmd/evconsole_router'; axios({ method:'post', url:url, headers: { 'Content-Type': 'application/json' }, data: body, auth: { username: username, password: password } }).then(function (response) { console.log("inside then"); console.log(response); }) .catch(function (error) { console.log("inside catch"); console.log(error); }); console.log("after axios"); })
当在特定日志文件中创建条目时,我试图将定义的 json 数据发送到 api url。我的控制台没有显示错误,但是数据也到达了 api。
这是我的日志:
> 0|server |
> {"@version":"1","host":"strproelk03","message":"60.16.48.61 - -
> [12/May/2020:23:24:06 -0600] \\\"GET /robots.txt HTTP/1.1\\ 404 443
> 20","ApplicationName":"Oasis","Severity":"ERROR","@timestamp":"2020-05-16T20:10:39.632Z","tagfile_path":"log.log"}
> 0|server | after axios
> 0|server | Watching...
在 axios 是我看到的最后一条消息之后,它不会进入我的代码的“内部”或“内部缓存”部分。为什么进不去?
编辑:我添加了超时并绕过了我的证书验证,如下所示:
axios.defaults.timeout = 1000; const http = require('http'); const https = require('https'); const httpAgent = new http.Agent({ rejectUnauthorized: false, }); const httpsAgent = new https.Agent({ rejectUnauthorized: false, }); axios({ method:'post', url:url, httpsAgent: httpsAgent, httpAgent: httpAgent, headers: {'Content-Type': 'application/json' }, auth: { username: username, password: password }
这仍然不会改变我的最终结果。仍然没有错误也没有数据传递。
但是,当我测试使用 curl 命令直接发送数据时,该 url 可以正常工作,并且没有任何问题。
解决方案
验证它实际上很简单;你只需要用这样的测试端点替换现有的 URL:https ://postman-echo.com/post ,然后你可以看到你收到错误或收到有效的响应。我的假设是您的请求无法到达服务器,并且由于未设置 Axios 的超时,因此 Axios 只是在等待。您是否尝试过通过邮递员访问端点?
推荐阅读
- unix - 在 Unix 中写入文件时如何附加字符串
- blazor-server-side - 服务器端 Blazor 应用程序的 ASP.NET Core 身份验证
- java - Android Firebase 数据库检查用户名是否已被使用
- image - 如何在颤动中缓存一小部分图像?
- reactjs - 为什么当我将组件放入
它的构造函数调用了两次? - sql - 有没有办法用大数据库优化一个简单的 SQL 请求
- angular - 在 Angular 7 中的表达式中连接表达式内的字符串
- java - 有没有办法从 ratpack ctx.next() 获得 Promise
- reactjs - 如何在 SnackbarProvider 的内容中获取变量值
- sql - 实体框架连接多个表很慢