我尝试使用promise-request并编写代码:
var pr = require('promise-request');
var options = {
method: 'POST',
uri: 'http://localhost:4000/user/login',
port: 4000,
form: {
login: 'login',
password: 'password'
},
json: true
};
pr(options)
.then(function(res) {
console.log(res);
})
.catch(function(err) {
console.log(err);
});
如果不使用端口选项,我会收到错误:
Error: connect ECONNREFUSED 127.0.0.1:80
如果我添加端口选项,错误就会消失,但在官方文档中不会写到您可以设置此选项。它的工作原理很奇怪,因为我在 uri 中设置了端口。我遇到错误,无法从服务器获取数据。我只得到错误:
undefined:1
<!DOCTYPE html>
^
SyntaxError: Unexpected token < in JSON at position 0
我使用 http 模块执行相同的请求,一切正常,也许我需要使用另一个模块?
最佳答案
使用axios或request而不是 promise-request
代码如下所示:
1.
axios.post('/user/login', {
login: 'login',
password: 'password'
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
2.
request.post({
url: '/user/login',
form: {
login: 'login',
password: 'password'
}
}, function(err, httpResponse, body) {
})
关于node.js - 请求 promise - 使用端口向服务器发送错误的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43843480/