我想使用axios向模拟/假后端API发出获取异步请求
这是代码:src / fakeBackend / feedbacks.js
const { createGuid } = require('../utils/guid')
const { users } = require('./users')
const feedback = {
extern: [
{
id: createGuid(),
userId: users[0].id,
message: '',
date: new Date(2016, 2, 3).valueOf(),
},
{
id: createGuid(),
userId: users[4].id,
message: '',
date: new Date(2018, 10, 2).valueOf(),
},
],
}
src / fakeBackend / mock.js
const axios = require("axios");
const { parse } = require("url");
const MockAdapter = require("axios-mock-adapter");
const { feedback } = require("./feedbacks");
const instance = axios.create();
const mock = new MockAdapter(instance);
const extractData = ({ data, params, url }) => {
const { query } = parse(url, true);
const parsedData = data && JSON.parse(data);
return { ...query, ...params, ...parsedData };
};
mock.onGet(/feedback.*/).reply(config => {
let parsed;
try {
parsed = extractData(config);
} catch (e) {
return [400, { message: "incorrect data format" }];
}
if (!parsed.product) {
return [400, { message: "Product id not specified" }];
}
const feedbackForProduct = feedback[parsed.product];
if (feedbackForProduct) {
return [200, { feedback: feedbackForProduct }];
}
return [404, { message: "No such product exists." }];
});
module.exports = { axios: instance };
src/client.js
我在函数getFeedbackByProductViewData中使用axios进行请求
const { axios } = require("./fakeBackend/mock");
const getFeedbackByProductViewData = async (product) => {
let feedback;
await axios.get('/feedback', {
params: {
product: product
}
})
.then((response) => {
console.log(response);
feedback = response.data;
}, (error) => {
console.log(error);
});
return feedback;
};
module.exports = { getFeedbackByProductViewData };
为什么Axios收到呼叫会返回404错误?我认为网址不正确。如何制作正确的网址来模拟假的后端?