11const express = require ( 'express' )
22const app = express ( )
33
4- const ACCESS_TOKEN_NAME = 'x-authorization-code'
5-
64// https://blog.ryo4004.net/web/306/
75// method: post のために必須
86const bodyParser = require ( 'body-parser' )
97app . use ( bodyParser . urlencoded ( { extended : true } ) )
108app . use ( bodyParser . json ( ) )
119
10+ const cookieParser = require ( 'cookie-parser' )
11+ app . use ( cookieParser ( ) )
12+
1213// Example directories as static files
1314app . use ( express . static ( 'src/static' ) )
1415
16+ const ACCESS_TOKEN_NAME = 'x-authorization-code'
17+
1518app . use ( ( req , res , next ) => {
16- res . header ( 'Access-Control-Allow-Origin' , '*' )
19+ // CORSリクエストでクレデンシャル(≒クッキー)を必要とする場合の注意点 - Qiita - https://qiita.com/kawaz/items/1e51c374b7a13c21b7e2
20+ // * だと withCredentials が動かない
21+ // res.header('Access-Control-Allow-Origin', '*')
22+ res . header ( 'Access-Control-Allow-Origin' , 'http://localhost:4000' )
23+ res . header ( 'Access-Control-Allow-Credentials' , true )
24+
1725 res . header (
1826 'Access-Control-Allow-Headers' ,
1927 // Chrome は OK で、 Firefox と IE11 がダメだったため、
2028 // '*' だと CORS 的に許可されないので、明示的にリクエストヘッダーの key 名を許可しています
2129 `origin, x-requested-with, content-type, accept, post-header, common-header, header1, ${ ACCESS_TOKEN_NAME } , X-User-Agent, X-Referer`
2230 // '*'
2331 )
32+
2433 // https://stackoverflow.com/questions/37897523/axios-get-access-to-response-header-fields
2534 // https://github.com/axios/axios/issues/606
2635 // Access-Control-Expose-Headers を追加しないとカスタムレスポンスヘッダーをブラウザに返すことはできない
@@ -38,6 +47,23 @@ app.get('/', function(req, res) {
3847 res . send ( 'Hello World' )
3948} )
4049
50+ /**
51+ * post '/set-cookie'
52+ */
53+ app . post ( '/set-cookie' , function ( req , res ) {
54+ const token = req . body . token
55+
56+ if ( token ) {
57+ res . cookie ( 'from-server-token' , token , { maxAge : 60000 , httpOnly : false } )
58+ }
59+
60+ res . send (
61+ JSON . stringify ( {
62+ apiResult : 'ok'
63+ } )
64+ )
65+ } )
66+
4167/**
4268 * get '/api-waiting-for-5-seconds'
4369 */
0 commit comments