Skip to content

Instantly share code, notes, and snippets.

@Vijaysinh
Created February 16, 2021 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vijaysinh/c2a70a46078beda8ec24693d3e1d7975 to your computer and use it in GitHub Desktop.
Save Vijaysinh/c2a70a46078beda8ec24693d3e1d7975 to your computer and use it in GitHub Desktop.
Node JS CORS Enable
var express = require('express');
var app = express();
var fs = require("fs");
const bodyParser = require("body-parser");
/** bodyParser.urlencoded(options)
* Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
* and exposes the resulting object (containing the keys and values) on req.body
*/
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/listUsers', function (req, res) {
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
console.log( data );
res.end( data );
});
})
app.post('/addUser', function (req, res) {
console.log(req.body.name);
try {
const data = fs.appendFileSync('user.txt',JSON.stringify(req.body))
} catch (err) {
console.error(err)
}
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
<script>
$.ajax({
headers: { "Accept": "application/json"},
type: 'POST',
url: 'http://127.0.0.1:8081/addUser',
crossDomain: true,
data:{"email":profile.getEmail()},
beforeSend: function(xhr){
xhr.withCredentials = true;
},
success: function(data, textStatus, request){
console.log(data);
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment