] 2
正如我使用邮递员测试的那样,此API正常工作。请帮助我
答案 0 :(得分:0)
使用this.httpOptions()
代替httpOptions
,您必须在某处定义this.httpOptions()
函数并从那里导入选项,
否则,请尝试下面的代码,现在就足够了:
postMember(Member): Observable<any> {
return this.http.post('http://localhost:8000/api/members/store', JSON.stringify(Member), {headers: this.getCommonHeaders()})
.map(res => res.json())
.catch(err => Observable.throw(err));
}
//function for fetching headers, you can define according to your need over here..
getCommonHeaders(){
let headers = new Headers();
headers.append('Content-Type','application/json');
return headers;
}
答案 1 :(得分:0)
我不知道您的代码发生了什么。但是我在项目工作中也遇到了同样的问题。但是我阅读了文档并妥善解决了。在您的屏幕截图中,我看到您正在发送一个传递请求的请求(正文值,标头为httpOptions),一切正常,但是请检查以下两点:
您正在运行localhost api服务。因此,您需要快速解决CORS(跨源资源共享)问题,该问题在服务器站点上应该是正确的,否则浏览器将不接受任何请求。
请输入我下面提到的httpOptions凭据。(请注意,我正在使用角度为7.2.14的GET请求)
getcategories():Observable<any> { const httpOptions = { headers: new HttpHeaders( { 'Authorization': 'Your Token', 'Content-Type': 'application/json' }) } return this.httpclient.get("http://localhost:8000/api/v1/categories/", httpOptions); }
谢谢。希望是最好的。
答案 2 :(得分:0)
Express服务器
const express = require("express");
const app = express();
const cors = require("cors");
app.use(function (req, res, next) {
//Enabling CORS
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization");
next();
});
app.post("/members",cors(), (req, res)=>{
console.log(req.body);
res.status(200).send({"message" : "data received"});
});
角侧: 在src文件夹中,创建json文件proxy.conf.json并粘贴以下代码:
{
"/api/*": {
"target": "http://localhost:8000",
"secure": false,
"logLevel": "debug"
}
}
在angular.json
中在架构师中,粘贴
"architect": {
"options": {
"proxyConfig": "src/proxy.conf.json"
}
}
在服务器端应该有一个与端点上具有相同端点的api,以便接收数据,否则将遇到错误500。