node 发出ajax请求
I use the term HTTP, but HTTPS is what should be used everywhere, therefore these examples use HTTPS instead of HTTP.
我使用HTTP一词,但是HTTPS是应该在所有地方使用的术语,因此这些示例使用HTTPS代替HTTP。
执行GET请求 (Perform a GET Request)
const https = require('https')
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'GET'
}
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
process.stdout.write(d)
})
})
req.on('error', (error) => {
console.error(error)
})
req.end()
执行POST请求 (Perform a POST Request)
const https = require('https')
const data = JSON.stringify({
todo: 'Buy the milk'
})
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
process.stdout.write(d)
})
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()
放入并删除 (PUT and DELETE)
PUT and DELETE requests use the same POST request format, and just change the options.method
value.
PUT和DELETE请求使用相同的POST请求格式,只需更改options.method
值即可。
node 发出ajax请求