简体   繁体   English

如何在不打开浏览器的情况下在 node.js 中使用 $.ajax

[英]How to use $.ajax without opening the browser in node.js

First of all, I'm kinda new in node.js.首先,我对 node.js 有点陌生。 I want use this code (it works in browser) $.ajax('/postmessage'{method: "POST",data:{message: 'foo', username: 'bar'}) without opening the browser and let it run while I am doing any other thing.我想使用此代码(它在浏览器中有效) $.ajax('/postmessage'{method: "POST",data:{message: 'foo', username: 'bar'})而不打开浏览器并让它运行当我在做任何其他事情时。 Is it possible ?是否可以 ? Or there is a better way ?或者有更好的方法吗?

thanks.谢谢。

edit: I tried use axios :编辑:我尝试使用 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); })

and I get the error 403 and my message is not sent.我收到错误 403 并且我的消息没有发送。

See the documentation :请参阅文档

By default, axios serializes JavaScript objects to JSON.默认情况下,axios 将 JavaScript 对象序列化为 JSON。 To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.要改为以 application/x-www-form-urlencoded 格式发送数据,您可以使用以下选项之一。

In node.js, you can use the querystring module as follows:在 node.js 中,您可以使用 querystring 模块,如下所示:

 var querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

You can also use the qs library.您还可以使用 qs 库。

You were almost there.你快到了。 There is one caveat.有一个警告。 The following:下列:

$.ajax('/postmessage'{method: "POST",data:{message: 'foo', username: 'bar'})

Sends this HTTP request:发送此 HTTP 请求:

POST /postMessage HTTP/1.1
Content-Type: application/x-www-form-urlencoded

message=foo&username=bar

Your use of axios would send the following:您使用 axios 会发送以下信息:

POST /postMessage HTTP/1.1
Content-Type: application/json

{"message":"foo", "username":"bar"}

This is indicated in the axios documentation and is a deliberate choice as one of the main use cases for axios is the consumption REST APIs.这在axios 文档有所说明,并且是经过深思熟虑的选择,因为 axios 的主要用例之一是消费 REST API。

node.js has a built-in querystring module, allowing you to feed a string as body content of the POST request to axios, as follows: 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); })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM