วิธีเพิ่มโทเค็นลงในส่วนหัวจากที่จัดเก็บในตัวเครื่องในไฟล์บริการเชิงมุม

วิธีเพิ่มโทเค็นลงในส่วนหัวจากที่จัดเก็บในเครื่องในไฟล์บริการเชิงมุม

นี่คือโหนด API ของฉันซึ่งฉันเรียกว่า.....

{
app.post('/add',auth,(req,res)=>{

    const token = req.header('access_token');
    console.log(req.header);
    const decoded = jwt.verify(token, "secretkey",{expiresIn:'24h'});

    item.create({
        product:req.body.product,
        desc:req.body.desc,
        price:req.body.price,
        quantity:req.body.quantity,
        seller_id : mongoose.Types.ObjectId(decoded._id)

    },(err,item)=>{
        if(err){
            return res.send(err);}
        else{
        res.send(item);}
    });
});
}

นี่คือไฟล์บริการเชิงมุมของฉัน

create(product_data: any) { 
    debugger

    let headers = new Headers();
    var token = localStorage.getItem('access_token');
    headers.append('access_token',token);
    return this.httpClient.post("/seller/add", JSON.stringify(product_data))
      .pipe(tap(res=>{
          console.log(res);
    }))
}

person Krishna Soni    schedule 25.03.2019    source แหล่งที่มา


คำตอบ (2)


หากเกิดปัญหาขึ้นเมื่อคุณพยายามเพิ่มส่วนหัว ฉันให้โค้ดของฉันใช้งานได้ดังนี้:

const headers = new Headers({
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        }); return this._http.post(url, body, { headers }).map((data: any) => data.json());
person Arm144    schedule 25.03.2019

คลาส HttpHeaders ไม่สามารถเปลี่ยนรูปได้ ดังนั้นจึงส่งคืนอ็อบเจ็กต์ที่ลอกแบบมาในทุกการดำเนินการแก้ไข (append(), set()...) ดังนั้น หากคุณต้องการสร้างอินสแตนซ์ของคลาส HttpHeaders ที่ว่างเปล่า คุณควรกำหนดอ็อบเจ็กต์ที่ถูกแก้ไขใหม่อีกครั้งเมื่อดำเนินการ append

create(product_data: any) { 
    const token = localStorage.getItem('access_token');
    let headers = new Headers();

    headers = headers.append('access_token', token);

    return this.httpClient.post("/seller/add", JSON.stringify(product_data), { headers })
      .pipe(tap(res =>{
          console.log(res);
    }));
}

นอกจากนี้ ในสถานการณ์นี้ คุณสามารถยกตัวอย่างคลาส HttpHeaders ได้โดยตรงจากส่วนหัวที่คุณต้องการ (แนวทางที่สะอาดกว่า) เช่นนี้ (ฉันได้ทำการแก้ไขโค้ดของคุณเล็กน้อย (const แทนที่จะเป็น var, เครื่องหมายคำพูด และการจัดรูปแบบ):

create(product_data: any) { 
    const token = localStorage.getItem('access_token');
    const headers = new Headers('access_token', token);

    return this.httpClient.post('/seller/add', JSON.stringify(product_data), { headers })
      .pipe(
        tap(res => console.log(res))
      );
}
person Elias Garcia    schedule 25.03.2019