项目想使用一个后端服务接口,但需要身份验证,

    于是给了一个登陆接口,使用虚拟账号登陆,登录账号,接口响应头setCookie,却不成功,因为跨域,接口为https://xxx.com,项目为localhost:8080

    于是使用webpack的devServer代理,原已经有了代理所有接口均代理至8888端口

    1. // 原代理
    2. devServer: {
    3. proxy: {
    4. context: () => true,
    5. target: 'http://localhost:8888'
    6. }
    7. }

    代理不生效,要改成和原来同样的格式才行

    1. // 修改后
    2. devServer: {
    3. proxy: [
    4. {
    5. context: '/autox/v1',
    6. target: 'https://xxx.com'
    7. },
    8. {
    9. context: () => true,
    10. target: 'http://localhost:8888'
    11. }
    12. ]
    13. }

    又发现代理失败,报错TSL不合格,代表无法代理去https,于是开启secure:false

    1. // 修改后
    2. devServer: {
    3. proxy: [
    4. {
    5. context: '/autox/v1',
    6. target: 'https://xxx.com',
    7. secure: false
    8. },
    9. {
    10. context: () => true,
    11. target: 'http://localhost:8888'
    12. }
    13. ]
    14. }

    这样就可以了,验证的请求setCookie成功了,下次发往localhost:8080的请求就都带上了cookie

    另外代理的细节chrome的network里无法查看,可用bypass函数可用来debug

    1. devServer: {
    2. proxy: [
    3. {
    4. context: '/autox/v1',
    5. target: 'https://xxx.com',
    6. secure: false,
    7. bypass: (req, res, options) => {
    8. console.log(req, res, options)
    9. }
    10. },
    11. ]
    12. }