[英]How to use $.ajax without opening the browser in node.js
首先,我對 node.js 有點陌生。 我想使用此代碼(它在瀏覽器中有效) $.ajax('/postmessage'{method: "POST",data:{message: 'foo', username: 'bar'})
而不打開瀏覽器並讓它運行當我在做任何其他事情時。 是否可以 ? 或者有更好的方法嗎?
謝謝。
編輯:我嘗試使用 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 並且我的消息沒有發送。
請參閱文檔:
默認情況下,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 庫。
你快到了。 有一個警告。 下列:
$.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 文檔中有所說明,並且是經過深思熟慮的選擇,因為 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); })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.