Access to XMLHttpRequest at 'https://aip.baidubce.com/oauth/2.0/token' from origin 'http://localhost:44203' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
遇到的错误消息与跨域资源共享(CORS)有关。CORS是由Web浏览器实施的安全功能,用于限制网页对不同于提供网页的域的请求。
在情况下,从http://localhost:44203
向https://aip.baidubce.com/oauth/2.0/token
发出请求,而https://aip.baidubce.com
上的服务器未配置为允许来自本地域的请求。
解决办法:
在本地机器上设置代理服务器,将请求转发到https://aip.baidubce.com
。这样,你的请求将来自与页面相同的域,就不会遇到CORS问题。
// 获取当前页面上名称为account的单元格
// 获取当前页面
var page = Forguncy.Page;
var AppID = page.getCell("AppID").getValue();
var APIKey = page.getCell("APIKey").getValue();
var SecretKey = page.getCell("SecretKey").getValue();
var AESKey = page.getCell("AESKey").getValue();
var access_tokenCell = page.getCell("access_token");
// 请求地址
const url = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${APIKey}&client_secret=${SecretKey}`;
// 创建XHR对象
const xhr = new XMLHttpRequest();
// 设置请求方法和URL
xhr.open('POST', url, true);
// 设置请求头
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Accept', 'application/json');
// 处理响应
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// 处理响应数据
const responseData = xhr.responseText;
alert("响应数据: " + responseData);
console.log('responseData: ' + responseData)
// 将JSON字符串解析为JavaScript对象
const responseObject = JSON.parse(responseData);
console.log('responseObject: ' + responseObject)
// 获取data值
const data = responseObject.data;
console.log('data: ' + data)
access_tokenCell.setValue(data.access_token);
// //获取页面上的表格
// var listview = page.getListView("表格1");
// //添加新行
// listview.addNewRow(jsonDataObject);
} else {
// 处理错误
console.error('Error:', xhr.status, xhr.statusText);
alert("Error" + xhr.status + " " + xhr.statusText);
}
}
};
// 发送请求
xhr.send(JSON.stringify(""));
修改后的代码:
// 获取当前页面上名称为account的单元格
// 获取当前页面
var page = Forguncy.Page;
var access_token = page.getCell("access_token").getValue();
var imageUrl = page.getCell("imageUrl").getValue();
var result=page.getCell("result");
//获取单元格的值
var data = {
//传入请求地址
token: access_token,
imageUrl: imageUrl
};
Forguncy.Helper.post("customapi/fapiaoapi/vatInvoice", data, function (res) {
console.log("res:"+res);
let jsonData=JSON.parse(res);
console.log(jsonData.words_result);
jsonData=JSON.stringify(jsonData.words_result);
console.log(jsonData);
result.setValue(res);
});
using GrapeCity.Forguncy.ServerApi;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using RestSharp;
using System.Net;
using System.Web;
namespace FaPiaoApi
{
public class FaPiaoApi : ForguncyApi
{
[Post]
public async Task GetTokenApi()
{
//获取post请求的数据
var form = await Context.Request.ReadFormAsync();
var url = form["url"][0];
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
var body = @"";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
//响应数据
await this.Context.Response.WriteAsync(response.Content);
}
[Post]
public async Task VatInvoice()
{
//获取post请求的数据
var form = await Context.Request.ReadFormAsync();
var token = form["token"][0];
var imageUrl = form["imageUrl"][0];
var client = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token=" + token);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.AddParameter("url", imageUrl);
request.AddParameter("seal_tag", "false");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
//响应数据
await this.Context.Response.WriteAsync(response.Content);
}
}
}
// 获取当前页面上名称为account的单元格
// 获取当前页面
var page = Forguncy.Page;
var access_token = page.getCell("access_token").getValue();
var imageUrl = page.getCell("imageUrl").getValue();
var resultCell = page.getCell("result");
var invoiceCodeCell = page.getCell("invoice_code");
var invoiceNumCell = page.getCell("invoice_num");
var invoiceDateCell = page.getCell("invoice_date");
var invoiceTypeCell = page.getCell("invoice_type");
var checkCodeCell = page.getCell("check_code");
var totalAmountCell = page.getCell("total_amount");
//获取单元格的值
var data = {
//传入请求地址
token: access_token,
imageUrl: imageUrl
};
Forguncy.Helper.post("customapi/fapiaoapi/vatInvoice", data, function (res) {
console.log("res:" + res);
let jsonData = JSON.parse(res);
jsonData = jsonData.words_result;
console.log(jsonData);
invoiceCodeCell.setValue(jsonData.InvoiceCode);
invoiceNumCell.setValue(jsonData.InvoiceNum);
invoiceDateCell.setValue(convertDateFormat(jsonData.InvoiceDate));
invoiceTypeCell.setValue(translateInvoiceType(jsonData.InvoiceType));
checkCodeCell.setValue(jsonData.CheckCode);
totalAmountCell.setValue(jsonData.TotalAmount);
resultCell.setValue(JSON.stringify(jsonData));
});
//日期格式转换
function convertDateFormat(inputDateString) {
// 使用正则表达式提取数字
var numbersArray = inputDateString.match(/\d+/g);
// 将数字字符串拼接在一起
var outputDateString = numbersArray.join("");
return outputDateString;
}
//发票种类格式转换
function translateInvoiceType(chineseInvoiceType) {
var translationMap = {
"增值税专用发票": "special_vat_invoice",
"增值税电子专用发票": "elec_special_vat_invoice",
"增值税普通发票": "normal_invoice",
"增值税普通发票(电子)": "elec_normal_invoice",
"电子发票(普通发票)": "elec_normal_invoice",
"增值税普通发票(卷式)": "roll_normal_invoice",
"通行费增值税电子普通发票": "toll_elec_normal_invoice",
"区块链电子发票(目前仅支持深圳地区)": "blockchain_invoice",
"全电发票(专用发票)": "elec_invoice_special",
"全电发票(普通发票)": "elec_invoice_normal",
"货运运输业增值税专用发票": "special_freight_transport_invoice",
"机动车销售发票": "motor_vehicle_invoice",
"二手车销售发票": "used_vehicle_invoice"
};
// 检查输入的中文发票类型是否在映射中,如果是则返回对应的英文翻译,否则返回原始值
for (var chineseType in translationMap) {
if (chineseInvoiceType.includes(chineseType)) {
return translationMap[chineseType];
}
}
// 如果未找到匹配的中文发票类型,则返回空值
return "";
}
using GrapeCity.Forguncy.ServerApi;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using RestSharp;
using System.Net;
using System.Web;
namespace FaPiaoApi
{
public class FaPiaoApi : ForguncyApi
{
[Post]
public async Task GetTokenApi()
{
//获取post请求的数据
var form = await Context.Request.ReadFormAsync();
var url = form["url"][0];
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
var body = @"";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
//响应数据
await this.Context.Response.WriteAsync(response.Content);
}
[Post]
public async Task VatInvoice()
{
//获取post请求的数据
var form = await Context.Request.ReadFormAsync();
var token = form["token"][0];
var imageUrl = form["imageUrl"][0];
var client = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token=" + token);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.AddParameter("url", imageUrl);
request.AddParameter("seal_tag", "false");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
//响应数据
await this.Context.Response.WriteAsync(response.Content);
}
[Post]
public async Task VatInvoiceVerification()
{
//获取post请求的数据
var form = await Context.Request.ReadFormAsync();
var token = form["token"][0];
var invoice_code = form["invoice_code"][0];
var invoice_num = form["invoice_num"][0];
var invoice_date = form["invoice_date"][0];
var invoice_type = form["invoice_type"][0];
var check_code = form["check_code"][0];
var total_amount = form["total_amount"][0];
var client = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice_verification?access_token=" + token);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.AddParameter("invoice_code", invoice_code);
request.AddParameter("invoice_num", invoice_num);
request.AddParameter("invoice_date", invoice_date);
request.AddParameter("invoice_type", invoice_type);
request.AddParameter("check_code", check_code);
request.AddParameter("total_amount", total_amount);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
//响应数据
await this.Context.Response.WriteAsync(response.Content);
}
}
}
// 获取当前页面上名称为account的单元格
// 获取当前页面
var page = Forguncy.Page;
var access_token = page.getCell("access_token").getValue();
var invoiceCode = page.getCell("invoice_code").getValue();
var invoiceNum = page.getCell("invoice_num").getValue();
var invoiceDate = page.getCell("invoice_date").getValue();
var invoiceType = page.getCell("invoice_type").getValue();
var checkCode = page.getCell("check_code").getValue();
var totalAmount = page.getCell("total_amount").getValue();
var verifyMessageCell= page.getCell("verifyMessage");
//获取单元格的值
var data = {
//传入请求地址
token: access_token,
invoice_code: invoiceCode,
invoice_num: invoiceNum,
invoice_date: invoiceDate,
invoice_type: invoiceType,
check_code: checkCode,
total_amount: totalAmount,
};
console.log("check_code:"+checkCode);
if(checkCode==""){
alert("check_code未检测到,无法验真");
}else{
Forguncy.Helper.post("customapi/fapiaoapi/vatinvoiceverification", data, function (res) {
console.log("res:" + res);
let jsonData = JSON.parse(res);
console.log(jsonData);
verifyMessageCell.setValue(jsonData.VerifyMessage);
});
}
1.增值税发票识别(bug:识别不出校验码)
2.增值税发票验真(bug:验真结果与实际情况不符)
验真功能调用后识别结果为不一致,我感觉是识别功能没把校验码识别出来导致的
试了很多次,校验码识别不出
这是我用来测试的增值税发票,这是发票在服务器minio中的url:http://47.109.133.206:9000/fapiao/fapiao.png
可以直接通过url访问这个图片