We can use the REST API below to achieve it.
https://sitecollectionurl/_api/SP.Web.CreateAnonymousLink
Example code:
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
anonymousAccessLink();
});
function anonymousAccessLink(){
var _selectedFileName = "a.xlsx";
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.Web.CreateAnonymousLink";
$.ajax({
'url': url,
'method': 'POST',
'data': JSON.stringify({
'url': _spPageContextInfo.webAbsoluteUrl + '/FolderName/' + _selectedFileName,
'isEditLink': false
}),
'headers': {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'X-RequestDigest': $('#__REQUESTDIGEST').val()
},
'success': function (data) {
var resultData = data.d.CreateAnonymousLink;
console.log(resultData);
},
'error': function (result, status) {
console.log("Ajax anonymous access :-"+JSON.stringify(result)+' - '+ status);
}
}); // End of ajax anonymous access.
}
</script>
Refer to: Rest Api Generate Guest Link SharePoint Online