Node.js 无法在Angular2中获得post工作
所以我尝试在我的angular应用程序中进行身份验证。我参加了会议,并创建了一个严格的机构。我还看了其他一些关于在postman中发送发帖请求的论坛帖子,但我无法让它正常工作Node.js 无法在Angular2中获得post工作,node.js,ionic2,ionic3,Node.js,Ionic2,Ionic3,所以我尝试在我的angular应用程序中进行身份验证。我参加了会议,并创建了一个严格的机构。我还看了其他一些关于在postman中发送发帖请求的论坛帖子,但我无法让它正常工作 getToken() { console.log('started getting of token'); //get username and password from local storage //Send username and password via body let
getToken()
{
console.log('started getting of token');
//get username and password from local storage
//Send username and password via body
let headers = new Headers();
let body = JSON.stringify({
name: 'test',
password: 'test'
});
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.jwt = this.http.post('http://localhost:8080/api/authenticate/', {
headers: headers,
body: body
}).map(res => res.text()).subscribe(data => console.log(data));
}
以上是我的代码。我知道这可能有点傻,但我无法让它工作。
我得到的错误是找不到用户。当用户名错误,并且数据库中不存在用户名时,就会发生这种情况。所以这也有点棘手
谁知道我犯了什么愚蠢的错误?使用以下代码发送post请求
this.jwt = this.http.post('http://localhost:8080/api/authenticate/',body,headers).map(res => res.text()).subscribe(data => console.log(data));
send_request_post(url: String, data:{})
{
var headerPost = new Headers
({
'Content-Type' : 'application/json ;charset=utf-8'
})
return this.http.post(url, JSON.stringify(data), {headers: headerPost})
.toPromise()
.then
(
response =>
{
console.log(response);
}
)
}
在service.ts文件中添加此代码
import { Http, URLSearchParams} from '@angular/http';
getToken()
{
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = new URLSearchParams();
body.set('name', test);
body.set('password', test);
return this.http.post("http://localhost:8080/api/authenticate/", body, headers).map(response => response.json());
}
此代码是我用于post请求的代码
this.jwt = this.http.post('http://localhost:8080/api/authenticate/',body,headers).map(res => res.text()).subscribe(data => console.log(data));
send_request_post(url: String, data:{})
{
var headerPost = new Headers
({
'Content-Type' : 'application/json ;charset=utf-8'
})
return this.http.post(url, JSON.stringify(data), {headers: headerPost})
.toPromise()
.then
(
response =>
{
console.log(response);
}
)
}
尝试
'Content-Type':'application/json'
很遗憾无法工作,感谢您的建议:)调试您的api,检查您的用户名和密码参数。我建议您删除json.stringify和Content-Type应用程序/x-www。。。。除非您非常确定后端需要它。如果您的后端是使用php构建的,那么默认情况下它可能不理解application/json。看看这个,我还注意到,您的postman只返回一个头,这在RESTAPI场景中是不可能的,因为在您的情况下,cors和内容类型是预期的。我认为调试GET请求可能比调试POST请求容易得多,以防问题出现在后端。检查您是否可以获取一个简单的JSON页面,这样做会让我得到一个空的主体。您只替换了“this.jwt=…”行,对吗?当然可以,我认为api有问题。因此,感谢您的帮助,我将继续调试。