Skip to content

Instantly share code, notes, and snippets.

@xgqfrms
Last active April 6, 2021 08:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xgqfrms/28436acbbc0b200b986ba263fa1176c1 to your computer and use it in GitHub Desktop.
Save xgqfrms/28436acbbc0b200b986ba263fa1176c1 to your computer and use it in GitHub Desktop.
Express.js Get HTTP POST json params
@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

express.js & Content-Security-Policy: connect-src

res.set("Content-Security-Policy", "default-src 'self'");

https://content-security-policy.com/examples/express-js/

app.use(function(req, res, next) {
    res.setHeader("Content-Security-Policy", "script-src 'self' https://apis.google.com");
    return next();
});

https://stackoverflow.com/questions/21048252/nodejs-where-exactly-can-i-put-the-content-security-policy

demo

app.use(function (req, res, next) {
  // JSON parse
  // console.log('req.body', req.body);
  // CORS bug
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  // res.header("Content-Security-Policy", "connect-src *");
  res.header("Content-Security-Policy", "connect-src '*'");
  // res.header("Content-Security-Policy", "connect-src localhost");
  // Content-Security-Policy: connect-src <source>;
  // Content-Security-Policy: connect-src <source> <source>;
  // res.header('Content-Type', 'application/json');
  // res.setHeader('Content-Type', 'application/json');
  next();
});

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

image

http://localhost:3000/api/get?q={%22username%22:%22xgqfrms%22}

fetch(`http://localhost:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST",
    mode: "cors",
})
.then(res => {
   console.log(`res =`, res)
   return res.json()
})
// .then(res => res.json())
.then(json => console.log(`json =`, json))
.catch(err => console.error(`error =`, err));

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment