如何避免为每个http请求手动设置application / json标头?

时间:2016-01-11 21:56:39

标签: angular

目前,我必须调用这样的所有内容,手动必须为每个请求添加正确的标头(并且还必须手动字符串化似乎......?)。有没有我可以定义标准头文件用于整个应用程序的地方?

@Injectable()
export class MyService {

    constructor(private http:Http) {
    }

    doSomething(data:MyObj) {
        return this.http.post('/api/somebackend',
            JSON.stringify(data),
            {
                headers: new Headers({
                    'Content-Type': 'application/json'
                })
            })
            .map(e => e.json())
            // ....
    }
}

2 个答案:

答案 0 :(得分:1)

看看这个问题:

How to make Angular 2 send all requests as application/x-www-form-urlencoded

你也可以这样做,只需添加标题'Content-Type': 'application/json'

答案 1 :(得分:-1)

很抱歉发帖作为答案,但我没有足够的代表发表评论。

您可以尝试使用类似here的拦截器。 所以你只能在一个地方定义它。