首先,我对node.js有点陌生。我想使用此代码(它在浏览器中有效)$.ajax('/postmessage'{method: "POST",data:{message: 'foo', username: 'bar'})
,而无需打开浏览器并在我执行任何其他操作时使其运行。
可能吗 ?还是有更好的方法?
谢谢。
edit:我尝试使用axios:
const axios = require('axios');
const instance = axios.create({ baseURL: 'sitehere' });
instance.post('/postmessage', { message: 'foo', username: 'bar'})
.then(
function (response) { console.log(response); })
.catch(
function (error) { console.log(error); })
我收到错误403,但消息未发送。
答案 0 :(得分:0)
默认情况下,axios将JavaScript对象序列化为JSON。发送数据 改为使用application / x-www-form-urlencoded格式,您可以使用 以下选项之一。
...
在node.js中,您可以按以下方式使用querystring模块:
var querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
您还可以使用qs库。
答案 1 :(得分:0)
您快到了。有一个警告。以下:
$.ajax('/postmessage'{method: "POST",data:{message: 'foo', username: 'bar'})
发送此HTTP请求:
POST /postMessage HTTP/1.1
Content-Type: application/x-www-form-urlencoded
message=foo&username=bar
您使用axios会发送以下信息:
POST /postMessage HTTP/1.1
Content-Type: application/json
{"message":"foo", "username":"bar"}
axios documentation中指出了这一点,这是有意选择的,因为axios的主要用例之一是消耗REST API。
node.js具有内置的querystring
模块,允许您将字符串作为POST请求的正文内容提供给axios,如下所示:
const axios = require('axios');
const querystring = require("querystring");
const instance = axios.create({ baseURL: 'sitehere' });
instance.post('/postmessage', querystring.stringify({ message: 'foo', username: 'bar'}))
.then(
function (response) { console.log(response); })
.catch(
function (error) { console.log(error); })